text:
package org.apache.derby.impl.store.raw.data;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.OutputStream;

import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.services.io.ArrayInputStream;
import org.apache.derby.iapi.services.io.CompressedNumber;
import org.apache.derby.iapi.services.io.DataInputUtil;
import org.apache.derby.iapi.services.sanity.SanityManager;

/**
    A class to provide static methods to manipulate fields in the field header.

	A class StoredPage uses to read/write field status and field data length.
	No attributes exist in this class, this class provides a set of static
	methods for writing field status and field data length, and for reading
	field status and field data length.

Stored Field Header Format

	The field header is broken into two sections.
    Only the Status byte is required to be there.

	Field header format:
	+--------+-------------------+
	| status | <fieldDataLength> |
	+--------+-------------------+
	Overflow page and overflow id are stored as field data.
	If the overflow bit in status is set, the field data is the overflow
    information.  When the overflow bit is not set in status, then,
	fieldData is the actually user data for the field.
	That means, field header consists only field status, and field data length.

	A non-overflow field:
	+--------+-------------------+-------------+
	| status | <fieldDataLength> | <fieldData> |
	+--------+-------------------+-------------+

	An overflow field:
	+--------+-------------------+-----------------+--------------+
	| status | <fieldDataLength> | <overflow page> | <overflowID> |
	+--------+-------------------+-----------------+--------------+

status

	The status is 1 byte, it indicates the state of the field.

	A FieldHeader can be in the following states:
	NULL		- if the field is NULL, no field data length is stored
	OVERFLOW	- indicates the field has been overflowed to another page.
				  overflow page and overflow ID is stored at the end of the
                  user data. field data length must be a number greater or
                  equal to 0, indicating the length of the field that is stored
                  on the current page.

				  The format looks like this:
				  +--------+-----------------+---------------+------------+
				  |<status>|<fieldDataLength>|<overflow page>|<overflowID>|
				  +--------+-----------------+---------------+------------+

				  overflowPage will be written as compressed long,
				  overflowId will be written as compressed Int

	NONEXISTENT	- the field no longer exists,
                  e.g. column has been dropped during an alter table

	EXTENSIBLE	- the field is of user defined data type.
                  The field may be tagged.

	TAGGED		- the field is TAGGED if and only if it is EXTENSIBLE.

	FIXED		- the field is FIXED if and only if it is used in the log
                  records for version 1.2 and higher.

fieldDataLength

	The fieldDataLength is only set if the field is not NULL.  It is the length
    of the field that is stored on the current page.
	The fieldDataLength is a variable length CompressedInt.

overflowPage and overflowID

	The overflowPage is a variable length CompressedLong, overflowID is a
    variable Length CompressedInt.
	They are only stored when the field state is OVERFLOW.
	And they are not stored in the field header.
	Instead, they are stored at the end of the field data.
	The reason we do that is to save a copy if the field has to overflow.

 MT - Mutable - Immutable identity - Thread Aware
*/
public final class StoredFieldHeader
{

    /**************************************************************************
     * Constants of the class
     **************************************************************************
     */

    // DO NOT use 0x80, some code reads byte into an int without masking the
    // sign bit, so do not use the high bit in the byte for a field status.
	private		static final int FIELD_INITIAL		= 0x00;
	public		static final int FIELD_NULL			= 0x01;
	public		static final int FIELD_OVERFLOW		= 0x02;
	private		static final int FIELD_NOT_NULLABLE	= 0x04;
	public		static final int FIELD_EXTENSIBLE	= 0x08;
	public		static final int FIELD_TAGGED		= 0x10;
	protected	static final int FIELD_FIXED		= 0x20;

	public		static final int FIELD_NONEXISTENT	= (FIELD_NOT_NULLABLE | FIELD_NULL);

    public static final int    STORED_FIELD_HEADER_STATUS_SIZE = 1;

    /**************************************************************************
     * Get accessors for testing bits in the status field.
     **************************************************************************
     */

	/**
		Get the status of the field

 MT - single thread required
	*/
	public static final boolean isNull(int status) {
		return ((status & FIELD_NULL) == FIELD_NULL);
	}

	public static final boolean isOverflow(int status) {
		return ((status & FIELD_OVERFLOW) == FIELD_OVERFLOW);
	}

	public static final boolean isNonexistent(int status) {
		return ((status & FIELD_NONEXISTENT) == FIELD_NONEXISTENT);
	}

	public static final boolean isExtensible(int status) {
		return ((status & FIELD_EXTENSIBLE) == FIELD_EXTENSIBLE);
	}

	public static final boolean isNullorNonExistent(int status) {
        // just need to check whether null bit is set.
        // return ((status & FIELD_NONEXISTENT) == FIELD_NONEXISTENT);
		return ((status & FIELD_NULL) != 0);
	}

	public static final boolean isTagged(int status) {
		//		if (SanityManager.DEBUG)
		//			SanityManager.ASSERT(isExtensible(status), "a field cannot be tagged if it is not extensible");
		return ((status & FIELD_TAGGED) == FIELD_TAGGED);
	}

	public static final boolean isFixed(int status) {
		return ((status & FIELD_FIXED) == FIELD_FIXED);
	}

	public static final boolean isNullable(int status) {
		return ((status & FIELD_NOT_NULLABLE) == 0);
	}

	public static final int size(
    int status,
    int fieldDataLength,
    int fieldDataSize)
    {

        if ((status & (FIELD_NULL | FIELD_FIXED)) == 0)
        {
            // usual case - not-null, not-fixed

            // WARNING - the following code hand inlined from
            // CompressedNumber for performance.
            //
            // return(CompressedNumber.sizeInt(fieldDataLength) + 1);
            //

            if (fieldDataLength <=
                        CompressedNumber.MAX_COMPRESSED_INT_ONE_BYTE)
            {
                // compressed form is 1 byte
                return(2);
            }
            else if (fieldDataLength <=
                        CompressedNumber.MAX_COMPRESSED_INT_TWO_BYTES)
            {
                // compressed form is 2 bytes
                return(3);
            }
            else
            {
                // compressed form is 4 bytes
                return(5);
            }
        }
        else if ((status & FIELD_NULL) != 0)
        {
            // field is null

			return(1);
		}
        else
        {
            // fixed length field

            return((fieldDataSize > 2) ? 5 : 3);
		}
	}

    /**************************************************************************
     * Set accessors for setting bits in the status field.
     **************************************************************************
     */

	public final static int setInitial() {
		return FIELD_INITIAL;
	}

	public final static int setNull(int status, boolean isNull) {
		if (isNull)
			status |= FIELD_NULL;
		else
			status &= ~FIELD_NULL;
		return status;
	}

	public final static int setOverflow(int status, boolean isOverflow) {
		if (isOverflow)
			status |= FIELD_OVERFLOW;
		else
			status &= ~FIELD_OVERFLOW;
		return status;
	}

	public final static int setNonexistent(int status) {
		status |= FIELD_NONEXISTENT;
		return status;
	}

	public final static int setExtensible(int status, boolean isExtensible) {
		if (isExtensible)
			status |= FIELD_EXTENSIBLE;
		else
			status &= ~FIELD_EXTENSIBLE;
		return status;
	}

	public final static int setTagged(int status, boolean isTagged) {

		if (SanityManager.DEBUG)
			SanityManager.ASSERT(isExtensible(status),
				"a field cannot be set to tagged if it is not extensible");

		if (isTagged)
			status |= FIELD_TAGGED;
		else
			status &= ~FIELD_TAGGED;
		return status;
	}

	public final static int setFixed(int status, boolean isFixed) {
		if (isFixed)
			status |= FIELD_FIXED;
		else
			status &= ~FIELD_FIXED;
		return status;
	}

    /**************************************************************************
     * routines used to write a field header to a OutputStream
     **************************************************************************
     */

	/**
		write out the field status and field data Length

		@exception IOException Thrown by potential I/O errors while writing
                               field header.
	 */
	public static final int write(
    OutputStream out,
    int status,
    int fieldDataLength,
    int fieldDataSize)
		throws IOException
    {
		int len = 1;

		out.write(status);

		if (isNull(status))
			return len;

		if (isFixed(status))
        {
			// if the field header is for log, we write it in compressed format,
			// then we pad the field, so the total length is fixed.
  			if (fieldDataSize > 2)
            {
				int diffLen =
                    fieldDataSize -
                    CompressedNumber.writeInt(out, fieldDataLength);

				for (int i = diffLen; i > 0; i--)
					out.write(0);
				len += fieldDataSize;	// size of an int - 4 bytes
			}
            else
            {
				// write the int out as a short
				out.write((fieldDataLength >>> 8) & 0xFF);
				out.write((fieldDataLength >>> 0) & 0xFF);
				len += 2;	// size of a short - 2 bytes
			}

			// NOTE: fixed version is used for logs only,
			// the overflow information is stored at the end of the optional
            // data, not in the field headers.
            // That's why we are not writing overflow info here.

		}
        else
        {
			// if we are writing the fieldHeader for the page,
            // we write in compressed format

			len += CompressedNumber.writeInt(out, fieldDataLength);
		}

		return len;
	}

    /**************************************************************************
     * routines used to read a field header from an ObjectInput stream, array
     **************************************************************************
     */

	/**
		read the field status

		@exception IOException Thrown by potential I/O errors while reading
                               field header.
	 */
	public static final int readStatus(ObjectInput in)
        throws IOException
    {
		int status;

		if ((status = in.read()) >= 0)
            return status;
        else
			throw new EOFException();
	}

	public static final int readStatus(
    byte[]      page,
    int         offset)
    {
        return(page[offset]);
    }

    /**
     * read the length of the field and hdr.
     *

     * Optimized routine used to skip a field on a page.  It returns the
     * total length of the field including the header portion.  It operates
     * directly on the array and does no checking of it's own for limits on
     * the array length, so an array out of bounds exception may be thrown -
     * the routine is meant to be used to read a field from a page so this
     * should not happen.
     *

     *
	 * @return The length of the field on the page, including it's header.
     *
     * @param data      the array where the field is.
     * @param offset    the offset in the array where the field begin, ie.
     *                  the status byte is at data[offset].
     *
	 * @exception  IOException  if an I/O error occurs
     **/
	public static final int readTotalFieldLength(
    byte[]      data,
    int         offset)
			throws IOException
    {
        if (SanityManager.DEBUG)
        {
            // this routine is meant to be called on the page, and FIXED fields
            // are only used in the log.

            if (isFixed(data[offset]))
                SanityManager.THROWASSERT("routine does not handle FIXED.");
        }

        if (((data[offset++]) & FIELD_NULL) != FIELD_NULL)
        {
            int value = data[offset];

            if ((value & ~0x3f) == 0)
            {
                // length is stored in this byte, we also know that the 0x80 bit
                // was not set, so no need to mask off the sign extension from
                // the byte to int conversion.

                // account for 1 byte stored length of field + 1 for status.
                return(value + 2);
            }
            else if ((value & 0x80) == 0)
            {
                // length stored in 2 bytes. only use low 6 bits from 1st byte.

                if (SanityManager.DEBUG)
                {
                    SanityManager.ASSERT((value & 0x40) == 0x40);
                }

                // top 8 bits of 2 byte length is stored in this byte, we also
                // know that the 0x80 bit was not set, so no need to mask off
                // the sign extension from the 1st byte to int conversion.  Need
                // to mask the byte in data[offset + 1] to account for possible
                // sign extension.

                // add 3 to account for 2 byte length + 1 for status

                return((((value & 0x3f) << 8) | (data[offset + 1] & 0xff)) + 3);
            }
            else
            {
                // length stored in 4 bytes.  only use low 7 bits from 1st byte.

                if (SanityManager.DEBUG)
                {
                    SanityManager.ASSERT((value & 0x80) == 0x80);
                }

                // top 8 bits of 4 byte length is stored in this byte, we also
                // know that the 0x80 bit was set, so need to mask off the
                // sign extension from the 1st byte to int conversion.  Need to
                // mask the bytes from the next 3 bytes data[offset + 1,2,3] to
                // account for possible sign extension.

                // add 5 to account for 4 byte length + 1 added to all returns
                return(
                    (((value            & 0x7f) << 24) |
                     ((data[offset + 1] & 0xff) << 16) |
                     ((data[offset + 2] & 0xff) <<  8) |
                      (data[offset + 3] & 0xff)) + 5);
            }
        }
        else
        {
            return(1);
        }
	}

	public static final int readFieldLengthAndSetStreamPosition(
    byte[]              data,
    int                 offset,
    int                 status,
    int                 fieldDataSize,
    ArrayInputStream    ais)
			throws IOException
    {
        if ((status & (FIELD_NULL | FIELD_FIXED)) == 0)
        {
            // usual case-not null, not fixed.  Length stored as compressed int.
            //   return(CompressedNumber.readInt(in));

            int value = data[offset++];

            if ((value & ~0x3f) == 0)
            {
                // usual case.

                // length is stored in this byte, we also know that the 0x80 bit
                // was not set, so no need to mask off the sign extension from
                // the byte to int conversion.

                // nothing to do, value already has int to return.

            }
            else if ((value & 0x80) == 0)
            {
                // length is stored in 2 bytes.  use low 6 bits from 1st byte.

                if (SanityManager.DEBUG)
                {
                    SanityManager.ASSERT((value & 0x40) == 0x40);
                }

                // top 8 bits of 2 byte length is stored in this byte, we also
                // know that the 0x80 bit was not set, so no need to mask off
                // the sign extension from the 1st byte to int conversion.
                // Need to mask the byte in data[offset + 1] to account for
                // possible sign extension.

                value = (((value & 0x3f) << 8) | (data[offset++] & 0xff));

            }
            else
            {
                // length is stored in 4 bytes.  only low 7 bits from 1st byte.

                if (SanityManager.DEBUG)
                {
                    SanityManager.ASSERT((value & 0x80) == 0x80);
                }

                // top 8 bits of 4 byte length is stored in this byte, we also
                // know that the 0x80 bit was set, so need to mask off the
                // sign extension from the 1st byte to int conversion.  Need to
                // mask the bytes from the next 3 bytes data[offset + 1,2,3] to
                // account for possible sign extension.

                // add 5 to account for 4 byte length + 1 added to all returns
                value =
                    (((value          & 0x7f) << 24) |
                     ((data[offset++] & 0xff) << 16) |
                     ((data[offset++] & 0xff) <<  8) |
                      (data[offset++] & 0xff));
            }

            ais.setPosition(offset);

            return(value);
        }
        else if ((status & FIELD_NULL) != 0)
        {
            ais.setPosition(offset);
            return(0);
        }
        else
        {
            int fieldDataLength;

            // field data length is in a fixed size field, not compressed.

            if (fieldDataSize <= 2)
            {
                // read it in as short, because it was written out as short
                fieldDataLength =
                    ((data[offset++] & 0xff) << 8) | (data[offset++] & 0xff);
            }
            else
            {
                // fieldDataLength = CompressedNumber.readInt(in);

                fieldDataLength = data[offset];

                if ((fieldDataLength & ~0x3f) == 0)
                {
                    // usual case.

                    // length is stored in this byte, we also know that the 0x80
                    // bit was not set, so no need to mask off the sign
                    // extension from the byte to int conversion.

                    // nothing to do, fieldDataLength already has int to return.

                }
                else if ((fieldDataLength & 0x80) == 0)
                {
                    // len is stored in 2 bytes.  use low 6 bits from 1st byte.

                    if (SanityManager.DEBUG)
                    {
                        SanityManager.ASSERT((fieldDataLength & 0x40) == 0x40);
                    }

                    // top 8 bits of 2 byte length is stored in this byte, we
                    // also know that the 0x80 bit was not set, so no need to
                    // mask off the sign extension from the 1st byte to int
                    // conversion.  Need to mask the byte in data[offset + 1] to
                    // account for possible sign extension.

                    fieldDataLength =
                        (((fieldDataLength & 0x3f) << 8) |
                         (data[offset + 1] & 0xff));

                }
                else
                {
                    // len is stored in 4 bytes.  only low 7 bits from 1st byte.

                    if (SanityManager.DEBUG)
                    {
                        SanityManager.ASSERT((fieldDataLength & 0x80) == 0x80);
                    }

                    // top 8 bits of 4 byte length is stored in this byte, we
                    // also know that the 0x80 bit was set, so need to mask off
                    // the sign extension from the 1st byte to int conversion.
                    // Need to mask the bytes from the next 3 bytes
                    // data[offset + 1,2,3] to account for possible sign
                    // extension.

                    fieldDataLength =
                        (((fieldDataLength  & 0x7f) << 24) |
                         ((data[offset + 1] & 0xff) << 16) |
                         ((data[offset + 2] & 0xff) <<  8) |
                          (data[offset + 3] & 0xff));
                }

                offset = offset + fieldDataSize;
            }

            ais.setPosition(offset);
            return(fieldDataLength);
        }

	}

	/**
		read the field data length

		@exception IOException Thrown by potential I/O errors while reading
                               field header.
	 */
	public static final int readFieldDataLength(
    ObjectInput in,
    int status,
    int fieldDataSize)
			throws IOException
    {

        if ((status & (FIELD_NULL | FIELD_FIXED)) == 0)
        {
            // usual case-not null, not fixed.  Length stored as compressed int.
            return(CompressedNumber.readInt(in));
        }
        else if ((status & FIELD_NULL) != 0)
        {
            // field is null or non-existent.
            return(0);
        }
        else
        {
            int fieldDataLength;

            // field data length is in a fixed size field, not compressed.

            if (fieldDataSize <= 2)
            {
                // read it in as short, because it was written out as short
                int ch1 = in.read();
                int ch2 = in.read();
                if ((ch1 | ch2) < 0)
                     throw new EOFException();

                fieldDataLength = ((ch1 << 8) + (ch2 << 0));
            }
            else
            {
                fieldDataLength =
                    CompressedNumber.readInt(in);

                int diffLen =
                    fieldDataSize -
                    CompressedNumber.sizeInt(fieldDataLength);

                if (diffLen != 0)
                    DataInputUtil.skipFully(in, diffLen);
            }

            return(fieldDataLength);
        }
	}

	public static String toDebugString(int status)
	{
		if (SanityManager.DEBUG)
		{
			StringBuffer str = new StringBuffer(100);
			if (isNull(status)) str.append("Null ");
			if (isOverflow(status)) str.append("Overflow ");
			if (isNonexistent(status)) str.append("Nonexistent ");
			if (isExtensible(status)) str.append("Extensible ");
			if (isTagged(status)) str.append("Tagged ");
			if (isFixed(status)) str.append("Fixed ");
			if (isNullable(status)) str.append("Nullable ");
			if (str.length() == 0)
				str.append("INITIAL ");

			return str.toString();
		}
		return null;
	}
}


text:
package squareup.options.misc;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface UnusedOption {
  boolean value();
}

redpajama_set_name: RedPajamaGithub


text:
export declare function setUp(done: Function): void;
export declare function testInitAreasScriptCreation(test: nodeunit.Test): void;
export declare function testAppConfigCreation(test: nodeunit.Test): void;
export declare function testAreasConfig(test: nodeunit.Test): void;
export declare function testAreasInitFiles(test: nodeunit.Test): void;
export declare function testRoutesConfig(test: nodeunit.Test): void;
export declare function testValuesConfig(test: nodeunit.Test): void;
export declare function testIndexPageScripts(test: nodeunit.Test): void;
export declare function testIndexPageStyles(test: nodeunit.Test): void;
export declare function testRebuildArea(test: nodeunit.Test): void;


text:
#ifndef PQCOMM_H
#define PQCOMM_H

#include <sys/socket.h>
#include <netdb.h>
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#include <netinet/in.h>

#ifdef HAVE_STRUCT_SOCKADDR_STORAGE

#ifndef HAVE_STRUCT_SOCKADDR_STORAGE_SS_FAMILY
#ifdef HAVE_STRUCT_SOCKADDR_STORAGE___SS_FAMILY
#define ss_family __ss_family
#else
#error struct sockaddr_storage does not provide an ss_family member
#endif
#endif

#ifdef HAVE_STRUCT_SOCKADDR_STORAGE___SS_LEN
#define ss_len __ss_len
#define HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN 1
#endif
#else							/* !HAVE_STRUCT_SOCKADDR_STORAGE */

/* Define a struct sockaddr_storage if we don't have one. */

struct sockaddr_storage
{
	union
	{
		struct sockaddr sa;		/* get the system-dependent fields */
		int64		ss_align;	/* ensures struct is properly aligned */
		char		ss_pad[128];	/* ensures struct has desired size */
	}			ss_stuff;
};

#define ss_family	ss_stuff.sa.sa_family
/* It should have an ss_len field if sockaddr has sa_len. */
#ifdef HAVE_STRUCT_SOCKADDR_SA_LEN
#define ss_len		ss_stuff.sa.sa_len
#define HAVE_STRUCT_SOCKADDR_STORAGE_SS_LEN 1
#endif
#endif   /* HAVE_STRUCT_SOCKADDR_STORAGE */

typedef struct
{
	struct sockaddr_storage addr;
	socklen_t salen;
} SockAddr;

/* Configure the UNIX socket location for the well known port. */

#define UNIXSOCK_PATH(path, port, sockdir) \
		snprintf(path, sizeof(path), "%s/.s.PGSQL.%d", \
				((sockdir) && *(sockdir) != '\0') ? (sockdir) : \
				DEFAULT_PGSOCKET_DIR, \
				(port))

/*
 * These manipulate the frontend/backend protocol version number.
 *
 * The major number should be incremented for incompatible changes.  The minor
 * number should be incremented for compatible changes (eg. additional
 * functionality).
 *
 * If a backend supports version m.n of the protocol it must actually support
 * versions m.[0..n].  Backend support for version m-1 can be dropped after a
 * `reasonable' length of time.
 *
 * A frontend isn't required to support anything other than the current
 * version.
 */
/* Upper four bits used special by GPDB */
#define PG_PROTOCOL_MAJOR(v)	(((v) >> 16) & 0xfff)
#define PG_PROTOCOL_MINOR(v)	((v) & 0x0000ffff)
#define PG_PROTOCOL(m,n)	(((m) << 16) | (n))

/* The earliest and latest frontend/backend protocol version supported. */

#define PG_PROTOCOL_EARLIEST	PG_PROTOCOL(1,0)
#define PG_PROTOCOL_LATEST		PG_PROTOCOL(3,0)

typedef uint32 ProtocolVersion; /* FE/BE protocol version number */

typedef ProtocolVersion MsgType;

/*
 * Packet lengths are 4 bytes in network byte order.
 *
 * The initial length is omitted from the packet layouts appearing below.
 */

typedef uint32 PacketLen;

/*
 * Old-style startup packet layout with fixed-width fields.  This is used in
 * protocol 1.0 and 2.0, but not in later versions.  Note that the fields
 * in this layout are '\0' terminated only if there is room.
 */

#define SM_DATABASE		64
#define SM_USER			32
/* We append database name if db_user_namespace true. */
#define SM_DATABASE_USER (SM_DATABASE+SM_USER+1)		/* +1 for @ */
#define SM_OPTIONS		64
#define SM_UNUSED		64
#define SM_TTY			64

typedef struct StartupPacket
{
	ProtocolVersion protoVersion;		/* Protocol version */
	char		database[SM_DATABASE];	/* Database name */
	/* Db_user_namespace appends dbname */
	char		user[SM_USER];	/* User name */
	char		options[SM_OPTIONS];	/* Optional additional args */
	char		unused[SM_UNUSED];		/* Unused */
	char		tty[SM_TTY];	/* Tty for debug output */
} StartupPacket;

extern bool Db_user_namespace;

/*
 * In protocol 3.0 and later, the startup packet length is not fixed, but
 * we set an arbitrary limit on it anyway.	This is just to prevent simple
 * denial-of-service attacks via sending enough data to run the server
 * out of memory.
 */
#define MAX_STARTUP_PACKET_LENGTH 64000

/* These are the authentication request codes sent by the backend. */

#define AUTH_REQ_OK			0	/* User is authenticated  */
#define AUTH_REQ_KRB4		1	/* Kerberos V4. Not supported any more. */
#define AUTH_REQ_KRB5		2	/* Kerberos V5 */
#define AUTH_REQ_PASSWORD	3	/* Password */
#define AUTH_REQ_CRYPT		4	/* crypt password. Not supported any more. */
#define AUTH_REQ_MD5		5	/* md5 password */
#define AUTH_REQ_SCM_CREDS	6	/* transfer SCM credentials */
#define AUTH_REQ_GSS		7	/* GSSAPI without wrap() */
#define AUTH_REQ_GSS_CONT	8	/* Continue GSS exchanges */
#define AUTH_REQ_SSPI		9	/* SSPI negotiate without wrap() */

typedef uint32 AuthRequest;

/*
 * A client can also send a cancel-current-operation request to the postmaster.
 * This is uglier than sending it directly to the client's backend, but it
 * avoids depending on out-of-band communication facilities.
 *
 * The cancel request code must not match any protocol version number
 * we're ever likely to use.  This random choice should do.
 */
#define CANCEL_REQUEST_CODE PG_PROTOCOL(1234,5678)

typedef struct CancelRequestPacket
{
	/* Note that each field is stored in network byte order! */
	MsgType		cancelRequestCode;		/* code to identify a cancel request */
	uint32		backendPID;		/* PID of client's backend */
	uint32		cancelAuthCode; /* secret key to authorize cancel */
} CancelRequestPacket;

/*
 * A client can also start by sending a SSL negotiation request, to get a
 * secure channel.
 */
#define NEGOTIATE_SSL_CODE PG_PROTOCOL(1234,5679)

/*
 * Filerep Add a pre-startup message primary-mirror-transition-request,
 * and a primary-mirror-transition-query
 */
#define PRIMARY_MIRROR_TRANSITION_REQUEST_CODE PG_PROTOCOL(1234,5680)
#define PRIMARY_MIRROR_TRANSITION_QUERY_CODE PG_PROTOCOL(1234,5681)

typedef struct PrimaryMirrorTransitionPacket
{
	MsgType protocolCode;
	uint32 dataLength;
} PrimaryMirrorTransitionPacket;

/* the number of times trying to acquire the send mutex for the front
 * end connection after detecting process is exitting */
#define PQ_BUSY_TEST_COUNT_IN_EXITING 5

#endif   /* PQCOMM_H */


text:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]-->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 1.5.2">
<title>lockfile API</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400">
<style>
/* Asciidoctor default stylesheet | MIT License | http://asciidoctor.org */
/* Remove the comments around the @import statement below when using this as a custom stylesheet */
/*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400";*/
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}
audio,canvas,video{display:inline-block}
audio:not([controls]){display:none;height:0}
[hidden],template{display:none}
script{display:none!important}
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
body{margin:0}
a{background:transparent}
a:focus{outline:thin dotted}
a:active,a:hover{outline:0}
h1{font-size:2em;margin:.67em 0}
abbr[title]{border-bottom:1px dotted}
b,strong{font-weight:bold}
dfn{font-style:italic}
hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}
mark{background:#ff0;color:#000}
code,kbd,pre,samp{font-family:monospace;font-size:1em}
pre{white-space:pre-wrap}
q{quotes:"\201C" "\201D" "\2018" "\2019"}
small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
figure{margin:0}
fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}
legend{border:0;padding:0}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}
input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}
input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}
textarea{overflow:auto;vertical-align:top}
table{border-collapse:collapse;border-spacing:0}
*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}
html,body{font-size:100%}
body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto}
a:hover{cursor:pointer}
img,object,embed{max-width:100%;height:auto}
object,embed{height:100%}
img{-ms-interpolation-mode:bicubic}
#map_canvas img,#map_canvas embed,#map_canvas object,.map_canvas img,.map_canvas embed,.map_canvas object{max-width:none!important}
.left{float:left!important}
.right{float:right!important}
.text-left{text-align:left!important}
.text-right{text-align:right!important}
.text-center{text-align:center!important}
.text-justify{text-align:justify!important}
.hide{display:none}
.antialiased,body{-webkit-font-smoothing:antialiased}
img{display:inline-block;vertical-align:middle}
textarea{height:auto;min-height:50px}
select{width:100%}
p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{font-size:1.21875em;line-height:1.6}
.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em}
div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}
a{color:#2156a5;text-decoration:underline;line-height:inherit}
a:hover,a:focus{color:#1d4b8f}
a img{border:none}
p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}
p aside{font-size:.875em;line-height:1.35;font-style:italic}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em}
h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0}
h1{font-size:2.125em}
h2{font-size:1.6875em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}
h4,h5{font-size:1.125em}
h6{font-size:1em}
hr{border:solid #ddddd8;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}
em,i{font-style:italic;line-height:inherit}
strong,b{font-weight:bold;line-height:inherit}
small{font-size:60%;line-height:inherit}
code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)}
ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}
ul,ol,ul.no-bullet,ol.no-bullet{margin-left:1.5em}
ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}
ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}
ul.square{list-style-type:square}
ul.circle{list-style-type:circle}
ul.disc{list-style-type:disc}
ul.no-bullet{list-style:none}
ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}
dl dt{margin-bottom:.3125em;font-weight:bold}
dl dd{margin-bottom:1.25em}
abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help}
abbr{text-transform:none}
blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}
blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)}
blockquote cite:before{content:"\2014 \0020"}
blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)}
blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)}
@media only screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}
h1{font-size:2.75em}
h2{font-size:2.3125em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em}
h4{font-size:1.4375em}}table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede}
table thead,table tfoot{background:#f7f8f7;font-weight:bold}
table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left}
table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)}
table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f8f8f7}
table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em}
h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400}
.clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table}
.clearfix:after,.float-group:after{clear:both}
*:not(pre)>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background-color:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed}
pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeSpeed}
.keyseq{color:rgba(51,51,51,.8)}
kbd{display:inline-block;color:rgba(0,0,0,.8);font-size:.75em;line-height:1.4;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:-.15em .15em 0 .15em;padding:.2em .6em .2em .5em;vertical-align:middle;white-space:nowrap}
.keyseq kbd:first-child{margin-left:0}
.keyseq kbd:last-child{margin-right:0}
.menuseq,.menu{color:rgba(0,0,0,.8)}
b.button:before,b.button:after{position:relative;top:-1px;font-weight:400}
b.button:before{content:"[";padding:0 3px 0 2px}
b.button:after{content:"]";padding:0 2px 0 3px}
p a>code:hover{color:rgba(0,0,0,.9)}
#header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em}
#header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table}
#header:after,#content:after,#footnotes:after,#footer:after{clear:both}
#content{margin-top:1.25em}
#content:before{content:none}
#header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0}
#header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #ddddd8}
#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #ddddd8;padding-bottom:8px}
#header .details{border-bottom:1px solid #ddddd8;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}
#header .details span:first-child{margin-left:-.125em}
#header .details span.email a{color:rgba(0,0,0,.85)}
#header .details br{display:none}
#header .details br+span:before{content:"\00a0\2013\00a0"}
#header .details br+span.author:before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)}
#header .details br+span#revremark:before{content:"\00a0|\00a0"}
#header #revnumber{text-transform:capitalize}
#header #revnumber:after{content:"\00a0"}
#content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #ddddd8;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem}
#toc{border-bottom:1px solid #efefed;padding-bottom:.5em}
#toc>ul{margin-left:.125em}
#toc ul.sectlevel0>li>a{font-style:italic}
#toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0}
#toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none}
#toc a{text-decoration:none}
#toc a:active{text-decoration:underline}
#toctitle{color:#7a2518;font-size:1.2em}
@media only screen and (min-width:768px){#toctitle{font-size:1.375em}
body.toc2{padding-left:15em;padding-right:0}
#toc.toc2{margin-top:0!important;background-color:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #efefed;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto}
#toc.toc2 #toctitle{margin-top:0;font-size:1.2em}
#toc.toc2>ul{font-size:.9em;margin-bottom:0}
#toc.toc2 ul ul{margin-left:0;padding-left:1em}
#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em}
body.toc2.toc-right{padding-left:0;padding-right:15em}
body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #efefed;left:auto;right:0}}@media only screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0}
#toc.toc2{width:20em}
#toc.toc2 #toctitle{font-size:1.375em}
#toc.toc2>ul{font-size:.95em}
#toc.toc2 ul ul{padding-left:1.25em}
body.toc2.toc-right{padding-left:0;padding-right:20em}}#content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
#content #toc>:first-child{margin-top:0}
#content #toc>:last-child{margin-bottom:0}
#footer{max-width:100%;background-color:rgba(0,0,0,.8);padding:1.25em}
#footer-text{color:rgba(255,255,255,.8);line-height:1.44}
.sect1{padding-bottom:.625em}
@media only screen and (min-width:768px){.sect1{padding-bottom:1.25em}}.sect1+.sect1{border-top:1px solid #efefed}
#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400}
#content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em}
#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}
#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none}
#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221}
.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}
.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic}
table.tableblock>caption.title{white-space:nowrap;overflow:visible;max-width:0}
.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{color:rgba(0,0,0,.85)}
table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit}
.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}
.admonitionblock>table td.icon{text-align:center;width:80px}
.admonitionblock>table td.icon img{max-width:none}
.admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase}
.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #ddddd8;color:rgba(0,0,0,.6)}
.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}
.exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px}
.exampleblock>.content>:first-child{margin-top:0}
.exampleblock>.content>:last-child{margin-bottom:0}
.sidebarblock{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
.sidebarblock>:first-child{margin-top:0}
.sidebarblock>:last-child{margin-bottom:0}
.sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center}
.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}
.literalblock pre,.listingblock pre:not(.highlight),.listingblock pre[class="highlight"],.listingblock pre[class^="highlight "],.listingblock pre.CodeRay,.listingblock pre.prettyprint{background:#f7f7f8}
.sidebarblock .literalblock pre,.sidebarblock .listingblock pre:not(.highlight),.sidebarblock .listingblock pre[class="highlight"],.sidebarblock .listingblock pre[class^="highlight "],.sidebarblock .listingblock pre.CodeRay,.sidebarblock .listingblock pre.prettyprint{background:#f2f1f1}
.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;padding:1em;font-size:.8125em}
.literalblock pre.nowrap,.literalblock pre[class].nowrap,.listingblock pre.nowrap,.listingblock pre[class].nowrap{overflow-x:auto;white-space:pre;word-wrap:normal}
@media only screen and (min-width:768px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:.90625em}}@media only screen and (min-width:1280px){.literalblock pre,.literalblock pre[class],.listingblock pre,.listingblock pre[class]{font-size:1em}}.literalblock.output pre{color:#f7f7f8;background-color:rgba(0,0,0,.9)}
.listingblock pre.highlightjs{padding:0}
.listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px}
.listingblock pre.prettyprint{border-width:0}
.listingblock>.content{position:relative}
.listingblock code[data-lang]:before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:#999}
.listingblock:hover code[data-lang]:before{display:block}
.listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:.5em;color:#999}
.listingblock.terminal pre .command:not([data-prompt]):before{content:"$"}
table.pyhltable{border-collapse:separate;border:0;margin-bottom:0;background:none}
table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0}
table.pyhltable td.code{padding-left:.75em;padding-right:0}
pre.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #ddddd8}
pre.pygments .lineno{display:inline-block;margin-right:.25em}
table.pyhltable .linenodiv{background:none!important;padding-right:0!important}
.quoteblock{margin:0 1em 1.25em 1.5em;display:table}
.quoteblock>.title{margin-left:-1.5em;margin-bottom:.75em}
.quoteblock blockquote,.quoteblock blockquote p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify}
.quoteblock blockquote{margin:0;padding:0;border:0}
.quoteblock blockquote:before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)}
.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}
.quoteblock .attribution{margin-top:.5em;margin-right:.5ex;text-align:right}
.quoteblock .quoteblock{margin-left:0;margin-right:0;padding:.5em 0;border-left:3px solid rgba(0,0,0,.6)}
.quoteblock .quoteblock blockquote{padding:0 0 0 .75em}
.quoteblock .quoteblock blockquote:before{display:none}
.verseblock{margin:0 1em 1.25em 1em}
.verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility}
.verseblock pre strong{font-weight:400}
.verseblock .attribution{margin-top:1.25rem;margin-left:.5ex}
.quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic}
.quoteblock .attribution br,.verseblock .attribution br{display:none}
.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.05em;color:rgba(0,0,0,.6)}
.quoteblock.abstract{margin:0 0 1.25em 0;display:block}
.quoteblock.abstract blockquote,.quoteblock.abstract blockquote p{text-align:left;word-spacing:0}
.quoteblock.abstract blockquote:before,.quoteblock.abstract blockquote p:first-of-type:before{display:none}
table.tableblock{max-width:100%;border-collapse:separate}
table.tableblock td>.paragraph:last-child p>p:last-child,table.tableblock th>p:last-child,table.tableblock td>p:last-child{margin-bottom:0}
table.spread{width:100%}
table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede}
table.grid-all th.tableblock,table.grid-all td.tableblock{border-width:0 1px 1px 0}
table.grid-all tfoot>tr>th.tableblock,table.grid-all tfoot>tr>td.tableblock{border-width:1px 1px 0 0}
table.grid-cols th.tableblock,table.grid-cols td.tableblock{border-width:0 1px 0 0}
table.grid-all *>tr>.tableblock:last-child,table.grid-cols *>tr>.tableblock:last-child{border-right-width:0}
table.grid-rows th.tableblock,table.grid-rows td.tableblock{border-width:0 0 1px 0}
table.grid-all tbody>tr:last-child>th.tableblock,table.grid-all tbody>tr:last-child>td.tableblock,table.grid-all thead:last-child>tr>th.tableblock,table.grid-rows tbody>tr:last-child>th.tableblock,table.grid-rows tbody>tr:last-child>td.tableblock,table.grid-rows thead:last-child>tr>th.tableblock{border-bottom-width:0}
table.grid-rows tfoot>tr>th.tableblock,table.grid-rows tfoot>tr>td.tableblock{border-width:1px 0 0 0}
table.frame-all{border-width:1px}
table.frame-sides{border-width:0 1px}
table.frame-topbot{border-width:1px 0}
th.halign-left,td.halign-left{text-align:left}
th.halign-right,td.halign-right{text-align:right}
th.halign-center,td.halign-center{text-align:center}
th.valign-top,td.valign-top{vertical-align:top}
th.valign-bottom,td.valign-bottom{vertical-align:bottom}
th.valign-middle,td.valign-middle{vertical-align:middle}
table thead th,table tfoot th{font-weight:bold}
tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}
tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold}
p.tableblock>code:only-child{background:none;padding:0}
p.tableblock{font-size:1em}
td>div.verse{white-space:pre}
ol{margin-left:1.75em}
ul li ol{margin-left:1.5em}
dl dd{margin-left:1.125em}
dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}
ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em}
ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none}
ul.unstyled,ol.unnumbered,ul.checklist{margin-left:.625em}
ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1em;font-size:.85em}
ul.checklist li>p:first-child>input[type="checkbox"]:first-child{width:1em;position:relative;top:1px}
ul.inline{margin:0 auto .625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden}
ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block}
ul.inline>li>*{display:block}
.unstyled dl dt{font-weight:400;font-style:normal}
ol.arabic{list-style-type:decimal}
ol.decimal{list-style-type:decimal-leading-zero}
ol.loweralpha{list-style-type:lower-alpha}
ol.upperalpha{list-style-type:upper-alpha}
ol.lowerroman{list-style-type:lower-roman}
ol.upperroman{list-style-type:upper-roman}
ol.lowergreek{list-style-type:lower-greek}
.hdlist>table,.colist>table{border:0;background:none}
.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}
td.hdlist1{padding-right:.75em;font-weight:bold}
td.hdlist1,td.hdlist2{vertical-align:top}
.literalblock+.colist,.listingblock+.colist{margin-top:-.5em}
.colist>table tr>td:first-of-type{padding:0 .75em;line-height:1}
.colist>table tr>td:last-of-type{padding:.25em 0}
.thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd}
.imageblock.left,.imageblock[style*="float: left"]{margin:.25em .625em 1.25em 0}
.imageblock.right,.imageblock[style*="float: right"]{margin:.25em 0 1.25em .625em}
.imageblock>.title{margin-bottom:0}
.imageblock.thumb,.imageblock.th{border-width:6px}
.imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em}
.image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0}
.image.left{margin-right:.625em}
.image.right{margin-left:.625em}
a.image{text-decoration:none}
span.footnote,span.footnoteref{vertical-align:super;font-size:.875em}
span.footnote a,span.footnoteref a{text-decoration:none}
span.footnote a:active,span.footnoteref a:active{text-decoration:underline}
#footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em}
#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em 0;border-width:1px 0 0 0}
#footnotes .footnote{padding:0 .375em;line-height:1.3;font-size:.875em;margin-left:1.2em;text-indent:-1.2em;margin-bottom:.2em}
#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none}
#footnotes .footnote:last-of-type{margin-bottom:0}
#content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0}
.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}
.gist .file-data>table td.line-data{width:99%}
div.unbreakable{page-break-inside:avoid}
.big{font-size:larger}
.small{font-size:smaller}
.underline{text-decoration:underline}
.overline{text-decoration:overline}
.line-through{text-decoration:line-through}
.aqua{color:#00bfbf}
.aqua-background{background-color:#00fafa}
.black{color:#000}
.black-background{background-color:#000}
.blue{color:#0000bf}
.blue-background{background-color:#0000fa}
.fuchsia{color:#bf00bf}
.fuchsia-background{background-color:#fa00fa}
.gray{color:#606060}
.gray-background{background-color:#7d7d7d}
.green{color:#006000}
.green-background{background-color:#007d00}
.lime{color:#00bf00}
.lime-background{background-color:#00fa00}
.maroon{color:#600000}
.maroon-background{background-color:#7d0000}
.navy{color:#000060}
.navy-background{background-color:#00007d}
.olive{color:#606000}
.olive-background{background-color:#7d7d00}
.purple{color:#600060}
.purple-background{background-color:#7d007d}
.red{color:#bf0000}
.red-background{background-color:#fa0000}
.silver{color:#909090}
.silver-background{background-color:#bcbcbc}
.teal{color:#006060}
.teal-background{background-color:#007d7d}
.white{color:#bfbfbf}
.white-background{background-color:#fafafa}
.yellow{color:#bfbf00}
.yellow-background{background-color:#fafa00}
span.icon>.fa{cursor:default}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note:before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip:before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning:before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000}
.conum[data-value]{display:inline-block;color:#fff!important;background-color:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold}
.conum[data-value] *{color:#fff!important}
.conum[data-value]+b{display:none}
.conum[data-value]:after{content:attr(data-value)}
pre .conum[data-value]{position:relative;top:-.125em}
b.conum *{color:inherit!important}
.conum:not([data-value]):empty{display:none}
h1,h2{letter-spacing:-.01em}
dt,th.tableblock,td.content{text-rendering:optimizeLegibility}
p,td.content{letter-spacing:-.01em}
p strong,td.content strong{letter-spacing:-.005em}
p,blockquote,dt,td.content{font-size:1.0625rem}
p{margin-bottom:1.25rem}
.sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em}
.exampleblock>.content{background-color:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc}
.print-only{display:none!important}
@media print{@page{margin:1.25cm .75cm}
*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important}
a{color:inherit!important;text-decoration:underline!important}
a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important}
a[href^="http:"]:not(.bare):after,a[href^="https:"]:not(.bare):after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em}
abbr[title]:after{content:" (" attr(title) ")"}
pre,blockquote,tr,img{page-break-inside:avoid}
thead{display:table-header-group}
img{max-width:100%!important}
p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3}
h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid}
#toc,.sidebarblock,.exampleblock>.content{background:none!important}
#toc{border-bottom:1px solid #ddddd8!important;padding-bottom:0!important}
.sect1{padding-bottom:0!important}
.sect1+.sect1{border:0!important}
#header>h1:first-child{margin-top:1.25rem}
body.book #header{text-align:center}
body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em 0}
body.book #header .details{border:0!important;display:block;padding:0!important}
body.book #header .details span:first-child{margin-left:0!important}
body.book #header .details br{display:block}
body.book #header .details br+span:before{content:none!important}
body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important}
body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always}
.listingblock code[data-lang]:before{display:block}
#footer{background:none!important;padding:0 .9375em}
#footer-text{color:rgba(0,0,0,.6)!important;font-size:.9em}
.hide-on-print{display:none!important}
.print-only{display:block!important}
.hide-for-print{display:none!important}
.show-for-print{display:inherit!important}}
</style>
</head>
<body class="article">
<div id="header">
<h1>lockfile API</h1>
</div>
<div id="content">
<div id="preamble">
<div class="sectionbody">
<div class="paragraph">
<p>The lockfile API serves two purposes:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Mutual exclusion and atomic file updates. When we want to change a
file, we create a lockfile <code><filename>.lock</code>, write the new file
contents into it, and then rename the lockfile to its final
destination <code><filename></code>. We create the <code><filename>.lock</code> file with
<code>O_CREAT|O_EXCL</code> so that we can notice and fail if somebody else has
already locked the file, then atomically rename the lockfile to its
final destination to commit the changes and unlock the file.</p>
</li>
<li>
<p>Automatic cruft removal. If the program exits after we lock a file
but before the changes have been committed, we want to make sure
that we remove the lockfile. This is done by remembering the
lockfiles we have created in a linked list and setting up an
<code>atexit(3)</code> handler and a signal handler that clean up the
lockfiles. This mechanism ensures that outstanding lockfiles are
cleaned up if the program exits (including when <code>die()</code> is called)
or if the program dies on a signal.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Please note that lockfiles only block other writers. Readers do not
block, but they are guaranteed to see either the old contents of the
file or the new contents of the file (assuming that the filesystem
implements <code>rename(2)</code> atomically).</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_calling_sequence">Calling sequence</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The caller:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Allocates a <code>struct lock_file</code> either as a static variable or on the
heap, initialized to zeros. Once you use the structure to call the
<code>hold_lock_file_*</code> family of functions, it belongs to the lockfile
subsystem and its storage must remain valid throughout the life of
the program (i.e. you cannot use an on-stack variable to hold this
structure).</p>
</li>
<li>
<p>Attempts to create a lockfile by passing that variable and the path
of the final destination (e.g. <code>$GIT_DIR/index</code>) to
<code>hold_lock_file_for_update</code> or <code>hold_lock_file_for_append</code>.</p>
</li>
<li>
<p>Writes new content for the destination file by either:</p>
</li>
<li>
<p>writing to the file descriptor returned by the <code>hold_lock_file_*</code>
functions (also available via <code>lock->fd</code>).</p>
</li>
<li>
<p>calling <code>fdopen_lock_file</code> to get a <code>FILE</code> pointer for the open
file and writing to the file using stdio.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>When finished writing, the caller can:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Close the file descriptor and rename the lockfile to its final
destination by calling <code>commit_lock_file</code> or <code>commit_lock_file_to</code>.</p>
</li>
<li>
<p>Close the file descriptor and remove the lockfile by calling
<code>rollback_lock_file</code>.</p>
</li>
<li>
<p>Close the file descriptor without removing or renaming the lockfile
by calling <code>close_lock_file</code>, and later call <code>commit_lock_file</code>,
<code>commit_lock_file_to</code>, <code>rollback_lock_file</code>, or <code>reopen_lock_file</code>.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>Even after the lockfile is committed or rolled back, the <code>lock_file</code>
object must not be freed or altered by the caller. However, it may be
reused; just pass it to another call of <code>hold_lock_file_for_update</code> or
<code>hold_lock_file_for_append</code>.</p>
</div>
<div class="paragraph">
<p>If the program exits before you have called one of <code>commit_lock_file</code>,
<code>commit_lock_file_to</code>, <code>rollback_lock_file</code>, or <code>close_lock_file</code>, an
<code>atexit(3)</code> handler will close and remove the lockfile, rolling back
any uncommitted changes.</p>
</div>
<div class="paragraph">
<p>If you need to close the file descriptor you obtained from a
<code>hold_lock_file_*</code> function yourself, do so by calling
<code>close_lock_file</code>. You should never call <code>close(2)</code> or <code>fclose(3)</code>
yourself! Otherwise the <code>struct lock_file</code> structure would still think
that the file descriptor needs to be closed, and a commit or rollback
would result in duplicate calls to <code>close(2)</code>. Worse yet, if you close
and then later open another file descriptor for a completely different
purpose, then a commit or rollback might close that unrelated file
descriptor.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_error_handling">Error handling</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The <code>hold_lock_file_*</code> functions return a file descriptor on success
or -1 on failure (unless <code>LOCK_DIE_ON_ERROR</code> is used; see below). On
errors, <code>errno</code> describes the reason for failure. Errors can be
reported by passing <code>errno</code> to one of the following helper functions:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">unable_to_lock_message</dt>
<dd>
<p>Append an appropriate error message to a <code>strbuf</code>.</p>
</dd>
<dt class="hdlist1">unable_to_lock_error</dt>
<dd>
<p>Emit an appropriate error message using <code>error()</code>.</p>
</dd>
<dt class="hdlist1">unable_to_lock_die</dt>
<dd>
<p>Emit an appropriate error message and <code>die()</code>.</p>
</dd>
</dl>
</div>
<div class="paragraph">
<p>Similarly, <code>commit_lock_file</code>, <code>commit_lock_file_to</code>, and
<code>close_lock_file</code> return 0 on success. On failure they set <code>errno</code>
appropriately, do their best to roll back the lockfile, and return -1.</p>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_flags">Flags</h2>
<div class="sectionbody">
<div class="paragraph">
<p>The following flags can be passed to <code>hold_lock_file_for_update</code> or
<code>hold_lock_file_for_append</code>:</p>
</div>
<div class="dlist">
<dl>
<dt class="hdlist1">LOCK_NO_DEREF</dt>
<dd>
<p>Usually symbolic links in the destination path are resolved
and the lockfile is created by adding ".lock" to the resolved
path. If <code>LOCK_NO_DEREF</code> is set, then the lockfile is created
by adding ".lock" to the path argument itself. This option is
used, for example, when locking a symbolic reference, which
for backwards-compatibility reasons can be a symbolic link
containing the name of the referred-to-reference.</p>
</dd>
<dt class="hdlist1">LOCK_DIE_ON_ERROR</dt>
<dd>
<p>If a lock is already taken for the file, <code>die()</code> with an error
message. If this option is not specified, trying to lock a
file that is already locked returns -1 to the caller.</p>
</dd>
</dl>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_the_functions">The functions</h2>
<div class="sectionbody">
<div class="dlist">
<dl>
<dt class="hdlist1">hold_lock_file_for_update</dt>
<dd>
<p>Take a pointer to <code>struct lock_file</code>, the path of the file to
be locked (e.g. <code>$GIT_DIR/index</code>) and a flags argument (see
above). Attempt to create a lockfile for the destination and
return the file descriptor for writing to the file.</p>
</dd>
<dt class="hdlist1">hold_lock_file_for_append</dt>
<dd>
<p>Like <code>hold_lock_file_for_update</code>, but before returning copy
the existing contents of the file (if any) to the lockfile and
position its write pointer at the end of the file.</p>
</dd>
<dt class="hdlist1">fdopen_lock_file</dt>
<dd>
<p>Associate a stdio stream with the lockfile. Return NULL
(<strong>without</strong> rolling back the lockfile) on error. The stream is
closed automatically when <code>close_lock_file</code> is called or when
the file is committed or rolled back.</p>
</dd>
<dt class="hdlist1">get_locked_file_path</dt>
<dd>
<p>Return the path of the file that is locked by the specified
lock_file object. The caller must free the memory.</p>
</dd>
<dt class="hdlist1">commit_lock_file</dt>
<dd>
<p>Take a pointer to the <code>struct lock_file</code> initialized with an
earlier call to <code>hold_lock_file_for_update</code> or
<code>hold_lock_file_for_append</code>, close the file descriptor, and
rename the lockfile to its final destination. Return 0 upon
success. On failure, roll back the lock file and return -1,
with <code>errno</code> set to the value from the failing call to
<code>close(2)</code> or <code>rename(2)</code>. It is a bug to call
<code>commit_lock_file</code> for a <code>lock_file</code> object that is not
currently locked.</p>
</dd>
<dt class="hdlist1">commit_lock_file_to</dt>
<dd>
<p>Like <code>commit_lock_file()</code>, except that it takes an explicit
<code>path</code> argument to which the lockfile should be renamed. The
<code>path</code> must be on the same filesystem as the lock file.</p>
</dd>
<dt class="hdlist1">rollback_lock_file</dt>
<dd>
<p>Take a pointer to the <code>struct lock_file</code> initialized with an
earlier call to <code>hold_lock_file_for_update</code> or
<code>hold_lock_file_for_append</code>, close the file descriptor and
remove the lockfile. It is a NOOP to call
<code>rollback_lock_file()</code> for a <code>lock_file</code> object that has
already been committed or rolled back.</p>
</dd>
<dt class="hdlist1">close_lock_file</dt>
<dd>
<p>Take a pointer to the <code>struct lock_file</code> initialized with an
earlier call to <code>hold_lock_file_for_update</code> or
<code>hold_lock_file_for_append</code>. Close the file descriptor (and
the file pointer if it has been opened using
<code>fdopen_lock_file</code>). Return 0 upon success. On failure to
<code>close(2)</code>, return a negative value and roll back the lock
file. Usually <code>commit_lock_file</code>, <code>commit_lock_file_to</code>, or
<code>rollback_lock_file</code> should eventually be called if
<code>close_lock_file</code> succeeds.</p>
</dd>
<dt class="hdlist1">reopen_lock_file</dt>
<dd>
<p>Re-open a lockfile that has been closed (using
<code>close_lock_file</code>) but not yet committed or rolled back. This
can be used to implement a sequence of operations like the
following:</p>
<div class="ulist">
<ul>
<li>
<p>Lock file.</p>
</li>
<li>
<p>Write new contents to lockfile, then <code>close_lock_file</code> to
cause the contents to be written to disk.</p>
</li>
<li>
<p>Pass the name of the lockfile to another program to allow it
(and nobody else) to inspect the contents you wrote, while
still holding the lock yourself.</p>
</li>
<li>
<p><code>reopen_lock_file</code> to reopen the lockfile. Make further
updates to the contents.</p>
</li>
<li>
<p><code>commit_lock_file</code> to make the final version permanent.</p>
</li>
</ul>
</div>
</dd>
</dl>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Last updated 2015-08-30 17:24:33 Coordinated Universal Time
</div>
</div>
</body>
</html>


text:
<?php

namespace Sonata\NotificationBundle\Tests\Entity;

use Sonata\NotificationBundle\Event\DoctrineOptimizeListener;
use Sonata\NotificationBundle\Event\IterateEvent;
use Sonata\NotificationBundle\Tests\Helpers\PHPUnit_Framework_TestCase;

class DoctrineOptimizeListenerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @expectedException \RuntimeException
     */
    public function testWithClosedManager()
    {
        $manager = $this->createMock('Doctrine\ORM\EntityManager');
        $manager->expects($this->once())->method('isOpen')->will($this->returnValue(false));

        $registry = $this->createMock('Symfony\Bridge\Doctrine\RegistryInterface');
        $registry->expects($this->once())->method('getManagers')->will($this->returnValue(array(
            'default' => $manager,
        )));

        $optimizer = new DoctrineOptimizeListener($registry);
        $optimizer->iterate(new IterateEvent(
            $this->getMock('Sonata\NotificationBundle\Iterator\MessageIteratorInterface'),
            $this->getMock('Sonata\NotificationBundle\Backend\BackendInterface')
        ));
    }

    public function testOptimize()
    {
        $unitofwork = $this->createMock('Doctrine\ORM\UnitOfWork');
        $unitofwork->expects($this->once())->method('clear');

        $manager = $this->createMock('Doctrine\ORM\EntityManager');
        $manager->expects($this->once())->method('isOpen')->will($this->returnValue(true));
        $manager->expects($this->once())->method('getUnitOfWork')->will($this->returnValue($unitofwork));

        $registry = $this->createMock('Symfony\Bridge\Doctrine\RegistryInterface');
        $registry->expects($this->once())->method('getManagers')->will($this->returnValue(array(
            'default' => $manager,
        )));

        $optimizer = new DoctrineOptimizeListener($registry);
        $optimizer->iterate(new IterateEvent(
            $this->createMock('Sonata\NotificationBundle\Iterator\MessageIteratorInterface'),
            $this->createMock('Sonata\NotificationBundle\Backend\BackendInterface')
        ));
    }
}


text:
namespace ConsoleTwiterTests.Messages
{
    using System;

    using ConsoleTwitter;
    using ConsoleTwitter.Messages;
    using ConsoleTwitter.Users;
    using ConsoleTwitter.Wrappers;

    using FluentAssertions;

    using NUnit.Framework;

    [TestFixture]
    public class MessageFormaterTests
    {
        private IMessageFormater formater;
        private Message message;

        [SetUp]
        public void Setup()
        {
            SystemTime.Now = () => new DateTime(2000, 1, 1);

            var userWall = new UserWall();
            var bob = new User("Bob", userWall);
            this.message = new Message(bob, "Bob's message");
            this.formater = new MessageFormater(new ElapsedTimeMessageFormater());
        }

        [Test]
        public void GivenAMessageWhenFormatIsCalledThenItFormatsTheMessageToProgramOutput()
        {
            var formatedMessage = this.formater.Format(this.message);

            formatedMessage.Should().Be("Bob's message (0 seconds ago)");
        }
    }
}


text:
module Azure::Hdinsight::Mgmt::V2015_03_01_preview
  module Models
    #
    # The load-based autoscale request parameters
    #
    class AutoscaleCapacity

      include MsRestAzure

      # @return [Integer] The minimum instance count of the cluster
      attr_accessor :min_instance_count

      # @return [Integer] The maximum instance count of the cluster
      attr_accessor :max_instance_count

      #
      # Mapper for AutoscaleCapacity class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'AutoscaleCapacity',
          type: {
            name: 'Composite',
            class_name: 'AutoscaleCapacity',
            model_properties: {
              min_instance_count: {
                client_side_validation: true,
                required: false,
                serialized_name: 'minInstanceCount',
                type: {
                  name: 'Number'
                }
              },
              max_instance_count: {
                client_side_validation: true,
                required: false,
                serialized_name: 'maxInstanceCount',
                type: {
                  name: 'Number'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
package com.tectonica.jonix.onix3;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.OnixComposite.OnixDataCompositeWithKey;
import com.tectonica.jonix.common.codelist.DiscountCodeTypes;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;
import com.tectonica.jonix.common.struct.JonixDiscountCoded;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Discount code composite

 *

 * An optional group of data elements which together define a discount code from a specified scheme, and repeatable to
 * allow different discount code schemes to be supported without defining additional data elements.
 *

 *

 * A discount code is generally used when the exact percentage discount (or commission, in an agency business model)
 * that a code represents may vary from reseller to reseller (or from agent to agent), or if terms must be kept
 * confidential. If the discount (or commission) is the same for all resellers (or agents) and need not be kept
 * confidential, use <Discount> and <DiscountPercent> instead.
 *

 *

 *

 * Reference name
 * <tt><DiscountCoded></tt>
 *

 *

 * Short tag
 * <tt><discountcoded></tt>
 *

 *

 * Cardinality
 * 0…n
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link Price}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ProductSupply} ⯈ {@link SupplyDetail} ⯈ {@link Reissue} ⯈
 * {@link Price} ⯈ {@link DiscountCoded}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ProductSupply} ⯈ {@link SupplyDetail} ⯈ {@link Price} ⯈
 * {@link DiscountCoded}

 *

 */
public class DiscountCoded implements OnixDataCompositeWithKey<JonixDiscountCoded, DiscountCodeTypes>, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "DiscountCoded";
    public static final String shortname = "discountcoded";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * (type: dt.DateOrDateTime)
     */
    public String datestamp;

    /**
     * (type: dt.NonEmptyString)
     */
    public String sourcename;

    public RecordSourceTypes sourcetype;

    /////////////////////////////////////////////////////////////////////////////////
    // CONSTRUCTION
    /////////////////////////////////////////////////////////////////////////////////

    private boolean initialized;
    private final boolean exists;
    private final org.w3c.dom.Element element;
    public static final DiscountCoded EMPTY = new DiscountCoded();

    public DiscountCoded() {
        exists = false;
        element = null;
        initialized = true; // so that no further processing will be done on this intentionally-empty object
    }

    public DiscountCoded(org.w3c.dom.Element element) {
        exists = true;
        initialized = false;
        this.element = element;
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcename = JPU.getAttribute(element, "sourcename");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));
    }

    @Override
    public void _initialize() {
        if (initialized) {
            return;
        }
        initialized = true;

        JPU.forElementsOf(element, e -> {
            final String name = e.getNodeName();
            switch (name) {
                case DiscountCodeType.refname:
                case DiscountCodeType.shortname:
                    discountCodeType = new DiscountCodeType(e);
                    break;
                case DiscountCode.refname:
                case DiscountCode.shortname:
                    discountCode = new DiscountCode(e);
                    break;
                case DiscountCodeTypeName.refname:
                case DiscountCodeTypeName.shortname:
                    discountCodeTypeName = new DiscountCodeTypeName(e);
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * @return whether this tag (<DiscountCoded> or <discountcoded>) is explicitly provided in the ONIX XML
     */
    @Override
    public boolean exists() {
        return exists;
    }

    @Override
    public org.w3c.dom.Element getXmlElement() {
        return element;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // MEMBERS
    /////////////////////////////////////////////////////////////////////////////////

    private DiscountCodeType discountCodeType = DiscountCodeType.EMPTY;

    /**
     *

     * An ONIX code identifying the scheme from which the value in the <DiscountCode> element is taken. Mandatory
     * in each occurrence of the <DiscountCoded> composite, and non-repeating.
     *

     * Jonix-Comment: this field is required
     */
    public DiscountCodeType discountCodeType() {
        _initialize();
        return discountCodeType;
    }

    private DiscountCode discountCode = DiscountCode.EMPTY;

    /**
     *

     * A discount code from the scheme specified in the <DiscountCodeType> element. Mandatory in each occurrence
     * of the <DiscountCoded> composite, and non-repeating.
     *

     * Jonix-Comment: this field is required
     */
    public DiscountCode discountCode() {
        _initialize();
        return discountCode;
    }

    private DiscountCodeTypeName discountCodeTypeName = DiscountCodeTypeName.EMPTY;

    /**
     *

     * A name which identifies a proprietary discount code. Must be used when, and only when the code in the
     * <DiscountCodeType> element indicates a proprietary scheme, eg a wholesaler's own code. Optional and
     * non-repeating.
     *

     * Jonix-Comment: this field is optional
     */
    public DiscountCodeTypeName discountCodeTypeName() {
        _initialize();
        return discountCodeTypeName;
    }

    @Override
    public JonixDiscountCoded asStruct() {
        _initialize();
        JonixDiscountCoded struct = new JonixDiscountCoded();
        struct.discountCodeType = discountCodeType.value;
        struct.discountCode = discountCode.value;
        struct.discountCodeTypeName = discountCodeTypeName.value;
        return struct;
    }

    @Override
    public DiscountCodeTypes structKey() {
        return discountCodeType().value;
    }
}


text:
package builder

import (
	"os"

	"github.com/fsouza/go-dockerclient"
	"github.com/openshift/source-to-image/pkg/sti/tar"
)

// DockerClient is an interface to the Docker client that contains
// the methods used by the common builder
type DockerClient interface {
	BuildImage(opts docker.BuildImageOptions) error
	PushImage(opts docker.PushImageOptions, auth docker.AuthConfiguration) error
	RemoveImage(name string) error
}

// pushImage pushes a docker image to the registry specified in its tag
func pushImage(client DockerClient, name string, authConfig docker.AuthConfiguration) error {
	repository, tag := docker.ParseRepositoryTag(name)
	opts := docker.PushImageOptions{
		Name:         repository,
		Tag:          tag,
		OutputStream: os.Stdout,
	}
	return client.PushImage(opts, authConfig)
}

func removeImage(client DockerClient, name string) error {
	return client.RemoveImage(name)
}

// buildImage invokes a docker build on a particular directory
func buildImage(client DockerClient, dir string, noCache bool, tag string, tar tar.Tar) error {
	tarFile, err := tar.CreateTarFile("", dir)
	if err != nil {
		return err
	}
	tarStream, err := os.Open(tarFile)
	if err != nil {
		return err
	}
	defer tarStream.Close()
	opts := docker.BuildImageOptions{
		Name:           tag,
		RmTmpContainer: true,
		OutputStream:   os.Stdout,
		InputStream:    tarStream,
		NoCache:        noCache,
	}
	return client.BuildImage(opts)
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TutPlanet2 : MonoBehaviour {
	Timer timer = new Timer();
	public GameObject tutorialText;

	void Start() {
	}

	void Update () {

		if (timer.time > 6) {
			tutorialText.SetActive(false);
			enabled = false;
		}
	}

	void OnCollisionEnter2D(Collision2D collision) {
		Player player = collision.gameObject.GetComponent<Player>();

		if (player != null && !tutorialText.activeInHierarchy) {
			if (player.cats.Count > 0) {
				enabled = false;
			} else if (enabled) {
				tutorialText.SetActive(true);
				timer.Start();
			}
		}
	}
}


text:
redirect_to: https://docs.gitlab.com/charts/installation/deployment.html#rbac
---

This document was moved to [another location](https://docs.gitlab.com/charts/installation/deployment.html#rbac).


text:
<!-- <ping-chart></ping-chart> -->
<!-- <impressions-chart></impressions-chart> -->

<iframe src="http://bl.ocks.org/tjdecke/raw/5558084/" height="430" scrolling="no"></iframe>


text:
<Record>
<Term>Conjugate Vaccines</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Immunologic Factor</SemanticType>
<ParentTerm>Vaccines, Synthetic</ParentTerm>
<ClassificationPath>Biological Factors/Antigens/Vaccines, Synthetic/Vaccines, Conjugate</ClassificationPath>
<ClassificationPath>Complex Mixtures/Biological Products/Vaccines/Vaccines, Synthetic/Vaccines, Conjugate</ClassificationPath>
<BroaderTerm>Vaccines, Conjugate</BroaderTerm>
<BroaderTerm>Biological Products</BroaderTerm>
<BroaderTerm>Biological Factors</BroaderTerm>
<BroaderTerm>Antigens</BroaderTerm>
<BroaderTerm>Vaccines, Synthetic</BroaderTerm>
<BroaderTerm>Vaccines</BroaderTerm>
<BroaderTerm>Complex Mixtures</BroaderTerm>
<Synonym>Conjugate Vaccines</Synonym>
<Description>Semisynthetic vaccines consisting of polysaccharide antigens from microorganisms attached to protein carrier molecules. The carrier protein is recognized by macrophages and T-cells thus enhancing immunity. Conjugate vaccines induce antibody formation in people not responsive to polysaccharide alone, induce higher levels of antibody, and show a booster response on repeated injection.</Description>
<Source>MeSH</Source>
</Record>


text:
module.exports = function notFound(data, options) {
  var req = this.req;
  var res = this.res;
  var sails = req._sails;
  res.status(404);
  if (data !== undefined) {
    sails.log.verbose('Sending 404 ("Not Found") response: \n', data);
  } else sails.log.verbose('Sending 404 ("Not Found") response');
  if (sails.config.environment === 'production' && sails.config.keepResponseErrors !== true) {
    data = undefined;
  }
  if (req.wantsJSON || sails.config.hooks.views === false) {
    return res.jsonx(data);
  }
  options = (typeof options === 'string') ? {
    view: options
  } : options || {};
  var viewData = data;
  if (!(viewData instanceof Error) && 'object' == typeof viewData) {
    try {
      viewData = require('util').inspect(data, {
        depth: null
      });
    } catch (e) {
      viewData = undefined;
    }
  }
  if (options.view) {
    return res.view(options.view, {
      data: viewData,
      title: 'Not Found'
    });
  } else return res.view('404', {
    data: viewData,
    title: 'Not Found'
  }, function(err, html) {
    if (err) {
      if (err.code === 'E_VIEW_FAILED') {
        sails.log.verbose('res.notFound() :: Could not locate view for error page (sending JSON instead).  Details: ', err);
      } else {
        sails.log.warn('res.notFound() :: When attempting to render error page view, an error occured (sending JSON instead).  Details: ', err);
      }
      return res.jsonx(data);
    }
    return res.send(html);
  });
};


text:
package org.apache.lucene.search;

import java.io.IOException;
import java.util.Objects;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.util.Bits;

/**
 * A query that wraps another query and ensures scores do not exceed a maximum value
 */
public final class CappedScoreQuery extends Query {
    private final Query query;
    private final float maxScore;

    /** Caps scores from the passed in Query to the supplied maxScore parameter */
    public CappedScoreQuery(Query query, float maxScore) {
        this.query = Objects.requireNonNull(query, "Query must not be null");
        if (maxScore > 0 == false) {
            throw new IllegalArgumentException(this.getClass().getName() + " maxScore must be >0, " + maxScore + " supplied.");
        }
        this.maxScore = maxScore;
    }

    /** Returns the encapsulated query. */
    public Query getQuery() {
        return query;
    }

    @Override
    public void visit(QueryVisitor visitor) {
        query.visit(visitor.getSubVisitor(BooleanClause.Occur.MUST, this));
    }

    @Override
    public Query rewrite(IndexReader reader) throws IOException {
        Query rewritten = query.rewrite(reader);

        if (rewritten != query) {
            return new CappedScoreQuery(rewritten, maxScore);
        }

        if (rewritten.getClass() == CappedScoreQuery.class) {
            return rewritten;
        }

        if (rewritten.getClass() == BoostQuery.class) {
            return new CappedScoreQuery(((BoostQuery) rewritten).getQuery(), maxScore);
        }

        return super.rewrite(reader);
    }

    /**
     * We return this as our {@link BulkScorer} so that if the CSQ wraps a query with its own optimized top-level scorer (e.g.
     * BooleanScorer) we can use that top-level scorer.
     */
    protected static class CappedBulkScorer extends BulkScorer {
        final BulkScorer bulkScorer;
        final Weight weight;
        final float maxScore;

        public CappedBulkScorer(BulkScorer bulkScorer, Weight weight, float maxScore) {
            this.bulkScorer = bulkScorer;
            this.weight = weight;
            this.maxScore = maxScore;
        }

        @Override
        public int score(LeafCollector collector, Bits acceptDocs, int min, int max) throws IOException {
            return bulkScorer.score(wrapCollector(collector), acceptDocs, min, max);
        }

        private LeafCollector wrapCollector(LeafCollector collector) {
            return new FilterLeafCollector(collector) {
                @Override
                public void setScorer(Scorable scorer) throws IOException {
                    // we must wrap again here, but using the scorer passed in as parameter:
                    in.setScorer(new FilterScorable(scorer) {
                        @Override
                        public float score() throws IOException {
                            return Math.min(maxScore, in.score());
                        }

                        @Override
                        public void setMinCompetitiveScore(float minScore) throws IOException {
                            scorer.setMinCompetitiveScore(minScore);
                        }

                    });
                }
            };
        }

        @Override
        public long cost() {
            return bulkScorer.cost();
        }
    }

    @Override
    public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
        final Weight innerWeight = searcher.createWeight(query, scoreMode, boost);
        if (scoreMode.needsScores()) {
            return new CappedScoreWeight(this, innerWeight, maxScore) {
                @Override
                public BulkScorer bulkScorer(LeafReaderContext context) throws IOException {
                    final BulkScorer innerScorer = innerWeight.bulkScorer(context);
                    if (innerScorer == null) {
                        return null;
                    }
                    return new CappedBulkScorer(innerScorer, this, maxScore);
                }

                @Override
                public ScorerSupplier scorerSupplier(LeafReaderContext context) throws IOException {
                    ScorerSupplier innerScorerSupplier = innerWeight.scorerSupplier(context);
                    if (innerScorerSupplier == null) {
                        return null;
                    }
                    return new ScorerSupplier() {
                        @Override
                        public Scorer get(long leadCost) throws IOException {
                            final Scorer innerScorer = innerScorerSupplier.get(leadCost);
                            // test scoreMode to avoid NPE - see https://github.com/elastic/elasticsearch/issues/51034
                            if (scoreMode == ScoreMode.TOP_SCORES) {
                                // short-circuit if scores will not need capping
                                innerScorer.advanceShallow(0);
                                if (innerScorer.getMaxScore(DocIdSetIterator.NO_MORE_DOCS) <= maxScore) {
                                  return innerScorer;
                                }
                            }
                            return new CappedScorer(innerWeight, innerScorer, maxScore);
                        }

                        @Override
                        public long cost() {
                            return innerScorerSupplier.cost();
                        }
                    };
                }

                @Override
                public Matches matches(LeafReaderContext context, int doc) throws IOException {
                    return innerWeight.matches(context, doc);
                }

                @Override
                public Scorer scorer(LeafReaderContext context) throws IOException {
                    ScorerSupplier scorerSupplier = scorerSupplier(context);
                    if (scorerSupplier == null) {
                        return null;
                    }
                    return scorerSupplier.get(Long.MAX_VALUE);
                }
            };
        } else {
            return innerWeight;
        }
    }

    @Override
    public String toString(String field) {
        return new StringBuilder("CappedScore(").append(query.toString(field)).append(')').toString();
    }

    @Override
    public boolean equals(Object other) {
        return sameClassAs(other) && maxScore == ((CappedScoreQuery) other).maxScore &&
                query.equals(((CappedScoreQuery) other).query);
    }

    @Override
    public int hashCode() {
        return 31 * classHash() + query.hashCode() + Float.hashCode(maxScore);
    }
}


text:
require 'rmagick'

puts <<END_INFO
This example creates an animated GIF that resembles the OS X "waiting" icon.
You can view the GIF with the command

    animate spinner.gif
END_INFO

NFRAMES = 12                    # number of frames in the animation
DIM = 32                        # width & height of image in pixels
DELAY = 100.0 / (NFRAMES/2)     # 2 rotations per second

# 'frame' is a single frame in the animation.
frame = Magick::Image.new(DIM, DIM) {self.background_color = 'transparent'}

# 'spinner' will contain the frames that make up the animated GIF
spinner = Magick::ImageList.new

# 'level' is the change from darkest gray to white
level = Magick::QuantumRange / 2 / NFRAMES

NFRAMES.times do |x|
  gc = Magick::Draw.new
  gc.translate(DIM/2, DIM/2)
  gc.stroke('none')
  intensity = 0.58 * Magick::QuantumRange
  fill_color = Magick::Pixel.new(intensity, intensity, intensity).to_color
  gc.fill(fill_color)
  angle = x * (360/NFRAMES)
  NFRAMES.times do
    gc.rotate(angle)
    intensity = [intensity, Magick::QuantumRange].min
    fill_color = Magick::Pixel.new(intensity, intensity, intensity).to_color
    gc.fill(fill_color)
    gc.roundrectangle(7, -1, 15, 0, 1, 1)
    angle = -(360/NFRAMES)
    intensity += level
  end
  spinner << frame.copy
  gc.draw(spinner)
end

spinner.delay = DELAY
spinner.compression = Magick::LZWCompression
spinner.write('spinner.gif')


text:
layout: portfolio
title: Collabolabs.co
date: 2015-04-22 11:30:49.000000000 +05:30
categories: []
tags: []
status: publish
type: portfolio
published: true
meta:
  _thumbnail_id: '4232'
  dsq_thread_id: '3703432232'
  _edit_last: '4'
  name: Collabolabs.co
  _jetpack_related_posts_cache: a:0:{}
author:
  login: cvlewis
  email: carl@carlvlewis.net
  display_name: Carl V. Lewis
  first_name: Carl V.
  last_name: Lewis
excerpt: !ruby/object:Hpricot::Doc
  options: {}
---

[caption id="attachment_4232" align="aligncenter" width="780"] Screenshot of sketch prototype, branding and hand-coded responsive landing page for CollaboLabs.co.[/caption]

[cta_button_wrap]View Project>>[/cta_button_wrap]


text:
import {inject, TestBed} from '@angular/core/testing';

import {Category} from './category';
import {CategoryService} from './category.service';
import {HttpService} from '../../shared/http.service';
import {AppConfig} from '../../app.config';

import {Observable} from 'rxjs/Observable';

describe('CategoryService', () => {

  /* stub definitions */
  class HttpServiceStub {
    get() {}
    post() {}
    delete() {}
  }
  class AppConfigStub {
    getCategoriesServiceUrl() {}
  }

  /* beforeEach definition */
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [CategoryService,
        { provide: AppConfig, useClass: AppConfigStub},
        { provide: HttpService, useClass: HttpServiceStub}
      ]
    });
  });

  /* Tests */

  it('should be created', inject([CategoryService], (service: CategoryService) => {
    expect(service).toBeTruthy();
  }));

  it('should get categories from api', inject(
    [CategoryService, HttpService, AppConfig],
    (service: CategoryService, httpService: HttpService, appConfig: AppConfig) => {
      const mockCategory = {
        id: 1,
        name: 'PENDING'
      };
      // Add spies
      spyOn(httpService, 'get').and.callFake(t => {
        return Observable.from([{
          json() {
            return [mockCategory];
          }
        }]);
      });
      spyOn(appConfig, 'getCategoriesServiceUrl').and.callFake(t => {
        return 'fakeUrl';
      });

      service.getCategories().subscribe(data => {
          expect(data.json()).toContain(mockCategory);
        }
      );

      expect(appConfig.getCategoriesServiceUrl).toHaveBeenCalledTimes(1);
      expect(httpService.get).toHaveBeenCalledWith('fakeUrl');
      expect(httpService.get).toHaveBeenCalledTimes(1);
    }));

  it('should get a category from api', inject(
    [CategoryService, HttpService, AppConfig],
    (service: CategoryService, httpService: HttpService, appConfig: AppConfig) => {
      const mockCategory = {
        id: 2,
        name: 'PENDING'
      };
      // Add spies
      spyOn(httpService, 'get').and.callFake(t => {
        return Observable.from([{
          json() {
            return mockCategory;
          }
        }]);
      });
      spyOn(appConfig, 'getCategoriesServiceUrl').and.callFake(t => {
        return 'fakeUrl2';
      });

      service.getCategory(1).subscribe(data => {
          expect(data.json()).toEqual(mockCategory);
        }
      );

      expect(appConfig.getCategoriesServiceUrl).toHaveBeenCalledTimes(1);
      expect(httpService.get).toHaveBeenCalledWith('fakeUrl2/1');
      expect(httpService.get).toHaveBeenCalledTimes(1);
    }));

  it('should save a category using api', inject(
    [CategoryService, HttpService, AppConfig],
    (service: CategoryService, httpService: HttpService, appConfig: AppConfig) => {
      const fakeCategory: Category = {
        id: 1,
        name: 'FakeCategory'
      };
      // Add spies
      spyOn(httpService, 'post').and.callFake(t => {
        return Observable.from([{
          json() {
            return fakeCategory;
          }
        }]);
      });
      spyOn(appConfig, 'getCategoriesServiceUrl').and.callFake(t => {
        return 'fakeUrl3';
      });

      service.saveCategory(fakeCategory).subscribe(data => {
          expect(data.json()).toEqual(fakeCategory);
        }
      );

      expect(appConfig.getCategoriesServiceUrl).toHaveBeenCalledTimes(1);
      expect(httpService.post).toHaveBeenCalledWith('fakeUrl3', fakeCategory);
      expect(httpService.post).toHaveBeenCalledTimes(1);
    }));

  it('should delete a category using api', inject(
    [CategoryService, HttpService, AppConfig],
    (service: CategoryService, httpService: HttpService, appConfig: AppConfig) => {
      const fakeCategory: Category = {
        id: 2,
        name: 'FakeCategory'
      };
      // Add spies
      spyOn(httpService, 'delete').and.callFake(t => {
        return Observable.from([{
          json() {
            return fakeCategory;
          }
        }]);
      });
      spyOn(appConfig, 'getCategoriesServiceUrl').and.callFake(t => {
        return 'fakeUrl4';
      });

      service.deleteCategory(2).subscribe(data => {
          expect(data.json()).toEqual(fakeCategory);
        }
      );

      expect(appConfig.getCategoriesServiceUrl).toHaveBeenCalledTimes(1);
      expect(httpService.delete).toHaveBeenCalledWith('fakeUrl4/2');
      expect(httpService.delete).toHaveBeenCalledTimes(1);
    }));

});