text:
/*
 * rfbproto.h - header file for the RFB protocol version 3.3
 *
 * Uses types CARD<n> for an n-bit unsigned integer, INT<n> for an n-bit signed
 * integer (for n = 8, 16 and 32).
 *
 * All multiple byte integers are in big endian (network) order (most
 * significant byte first).  Unless noted otherwise there is no special
 * alignment of protocol structures.
 *
 *
 * Once the initial handshaking is done, all messages start with a type byte,
 * (usually) followed by message-specific data.  The order of definitions in
 * this file is as follows:
 *
 *  (1) Structures used in several types of message.
 *  (2) Structures used in the initial handshaking.
 *  (3) Message types.
 *  (4) Encoding types.
 *  (5) For each message type, the form of the data following the type byte.
 *      Sometimes this is defined by a single structure but the more complex
 *      messages have to be explained by comments.
 */

/*****************************************************************************
 *
 * Structures used in several messages
 *
 *****************************************************************************/

#include "inttypes.h"
#define CARD8  uint8_t
#define CARD16 uint16_t
#define CARD32 uint32_t

/*-----------------------------------------------------------------------------
 * Structure used to specify a rectangle.  This structure is a multiple of 4
 * bytes so that it can be interspersed with 32-bit pixel data without
 * affecting alignment.
 */
typedef struct {
    CARD16 x;
    CARD16 y;
    CARD16 w;
    CARD16 h;
} rfbRectangle;

#define sz_rfbRectangle 8

/*-----------------------------------------------------------------------------
 * Structure used to specify pixel format.
 */

typedef struct {

    CARD8 bitsPerPixel;		/* 8,16,32 only */

    CARD8 depth;		/* 8 to 32 */

    CARD8 bigEndian;		/* True if multi-byte pixels are interpreted
				   as big endian, or if single-bit-per-pixel
				   has most significant bit of the byte
				   corresponding to first (leftmost) pixel. Of
				   course this is meaningless for 8 bits/pix */

    CARD8 trueColour;		/* If false then we need a "colour map" to
				   convert pixels to RGB.  If true, xxxMax and
				   xxxShift specify bits used for red, green
				   and blue */

    /* the following fields are only meaningful if trueColour is true */

    CARD16 redMax;		/* maximum red value (= 2^n - 1 where n is the
				   number of bits used for red). Note this
				   value is always in big endian order. */

    CARD16 greenMax;		/* similar for green */

    CARD16 blueMax;		/* and blue */

    CARD8 redShift;		/* number of shifts needed to get the red
				   value in a pixel to the least significant
				   bit. To find the red value from a given
				   pixel, do the following:
				   1) Swap pixel value according to bigEndian
				      (e.g. if bigEndian is false and host byte
				      order is big endian, then swap).
				   2) Shift right by redShift.
				   3) AND with redMax (in host byte order).
				   4) You now have the red value between 0 and
				      redMax. */

    CARD8 greenShift;		/* similar for green */

    CARD8 blueShift;		/* and blue */

    CARD8 pad1;
    CARD16 pad2;

} rfbPixelFormat;

#define sz_rfbPixelFormat 16

/*****************************************************************************
 *
 * Initial handshaking messages
 *
 *****************************************************************************/

/*-----------------------------------------------------------------------------
 * Protocol Version
 *
 * The server always sends 12 bytes to start which identifies the latest RFB
 * protocol version number which it supports.  These bytes are interpreted
 * as a string of 12 ASCII characters in the format "RFB xxx.yyy\n" where
 * xxx and yyy are the major and minor version numbers (for version 3.3
 * this is "RFB 003.003\n").
 *
 * The client then replies with a similar 12-byte message giving the version
 * number of the protocol which should actually be used (which may be different
 * to that quoted by the server).
 *
 * It is intended that both clients and servers may provide some level of
 * backwards compatibility by this mechanism.  Servers in particular should
 * attempt to provide backwards compatibility, and even forwards compatibility
 * to some extent.  For example if a client demands version 3.1 of the
 * protocol, a 3.0 server can probably assume that by ignoring requests for
 * encoding types it doesn't understand, everything will still work OK.  This
 * will probably not be the case for changes in the major version number.
 *
 * The format string below can be used in sprintf or sscanf to generate or
 * decode the version string respectively.
 */

#define rfbProtocolVersionFormat "RFB %03d.%03d\n"
#define rfbProtocolMajorVersion 3
#define rfbProtocolMinorVersion 3

typedef char rfbProtocolVersionMsg[13];	/* allow extra byte for null */

#define sz_rfbProtocolVersionMsg 12

/*-----------------------------------------------------------------------------
 * Authentication
 *
 * Once the protocol version has been decided, the server then sends a 32-bit
 * word indicating whether any authentication is needed on the connection.
 * The value of this word determines the authentication scheme in use.  For
 * version 3.0 of the protocol this may have one of the following values:
 */

#define rfbConnFailed 0
#define rfbNoAuth 1
#define rfbVncAuth 2

/*
 * rfbConnFailed:	For some reason the connection failed (e.g. the server
 *			cannot support the desired protocol version).  This is
 *			followed by a string describing the reason (where a
 *			string is specified as a 32-bit length followed by that
 *			many ASCII characters).
 *
 * rfbNoAuth:		No authentication is needed.
 *
 * rfbVncAuth:		The VNC authentication scheme is to be used.  A 16-byte
 *			challenge follows, which the client encrypts as
 *			appropriate using the password and sends the resulting
 *			16-byte response.  If the response is correct, the
 *			server sends the 32-bit word rfbVncAuthOK.  If a simple
 *			failure happens, the server sends rfbVncAuthFailed and
 *			closes the connection. If the server decides that too
 *			many failures have occurred, it sends rfbVncAuthTooMany
 *			and closes the connection.  In the latter case, the
 *			server should not allow an immediate reconnection by
 *			the client.
 */

#define rfbVncAuthOK 0
#define rfbVncAuthFailed 1
#define rfbVncAuthTooMany 2

/*-----------------------------------------------------------------------------
 * Client Initialisation Message
 *
 * Once the client and server are sure that they're happy to talk to one
 * another, the client sends an initialisation message.  At present this
 * message only consists of a boolean indicating whether the server should try
 * to share the desktop by leaving other clients connected, or give exclusive
 * access to this client by disconnecting all other clients.
 */

typedef struct {
    CARD8 shared;
} rfbClientInitMsg;

#define sz_rfbClientInitMsg 1

/*-----------------------------------------------------------------------------
 * Server Initialisation Message
 *
 * After the client initialisation message, the server sends one of its own.
 * This tells the client the width and height of the server's framebuffer,
 * its pixel format and the name associated with the desktop.
 */

typedef struct {
    CARD16 framebufferWidth;
    CARD16 framebufferHeight;
    rfbPixelFormat format;	/* the server's preferred pixel format */
    CARD32 nameLength;
    /* followed by char name[nameLength] */
} rfbServerInitMsg;

#define sz_rfbServerInitMsg (8 + sz_rfbPixelFormat)

/*
 * Following the server initialisation message it's up to the client to send
 * whichever protocol messages it wants.  Typically it will send a
 * SetPixelFormat message and a SetEncodings message, followed by a
 * FramebufferUpdateRequest.  From then on the server will send
 * FramebufferUpdate messages in response to the client's
 * FramebufferUpdateRequest messages.  The client should send
 * FramebufferUpdateRequest messages with incremental set to true when it has
 * finished processing one FramebufferUpdate and is ready to process another.
 * With a fast client, the rate at which FramebufferUpdateRequests are sent
 * should be regulated to avoid hogging the network.
 */

/*****************************************************************************
 *
 * Message types
 *
 *****************************************************************************/

/* server -> client */

#define rfbFramebufferUpdate 0
#define rfbSetColourMapEntries 1
#define rfbBell 2
#define rfbServerCutText 3
#define rfbReSizeFrameBuffer 0xF

/* client -> server */

#define rfbSetPixelFormat 0
#define rfbFixColourMapEntries 1	/* not currently supported */
#define rfbSetEncodings 2
#define rfbFramebufferUpdateRequest 3
#define rfbKeyEvent 4
#define rfbPointerEvent 5
#define rfbClientCutText 6
#define rfbSetScaleFactor 0xF

/*****************************************************************************
 *
 * Encoding types
 *
 *****************************************************************************/

#define rfbEncodingRaw 0
#define rfbEncodingCopyRect 1
#define rfbEncodingRRE 2
#define rfbEncodingCoRRE 4
#define rfbEncodingHextile 5
#define rfbEncodingZRLE 16

/*****************************************************************************
 *
 * Server -> client message definitions
 *
 *****************************************************************************/

/*-----------------------------------------------------------------------------
 * FramebufferUpdate - a block of rectangles to be copied to the framebuffer.
 *
 * This message consists of a header giving the number of rectangles of pixel
 * data followed by the rectangles themselves.  The header is padded so that
 * together with the type byte it is an exact multiple of 4 bytes (to help
 * with alignment of 32-bit pixels):
 */

typedef struct {
    CARD8 type;			/* always rfbFramebufferUpdate */
    CARD8 pad;
    CARD16 nRects;
    /* followed by nRects rectangles */
} rfbFramebufferUpdateMsg;

#define sz_rfbFramebufferUpdateMsg 4

/*
 * Each rectangle of pixel data consists of a header describing the position
 * and size of the rectangle and a type word describing the encoding of the
 * pixel data, followed finally by the pixel data.  Note that if the client has
 * not sent a SetEncodings message then it will only receive raw pixel data.
 * Also note again that this structure is a multiple of 4 bytes.
 */

typedef struct {
    rfbRectangle r;
    CARD32 encoding;	/* one of the encoding types rfbEncoding... */
} rfbFramebufferUpdateRectHeader;

#define sz_rfbFramebufferUpdateRectHeader (sz_rfbRectangle + 4)

/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * Raw Encoding.  Pixels are sent in top-to-bottom scanline order,
 * left-to-right within a scanline with no padding in between.
 */

/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * CopyRect Encoding.  The pixels are specified simply by the x and y position
 * of the source rectangle.
 */

typedef struct {
    CARD16 srcX;
    CARD16 srcY;
} rfbCopyRect;

#define sz_rfbCopyRect 4

/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * RRE - Rise-and-Run-length Encoding.  We have an rfbRREHeader structure
 * giving the number of subrectangles following.  Finally the data follows in
 * the form [<bgpixel><subrect><subrect>...] where each <subrect> is
 * [<pixel><rfbRectangle>].
 */

typedef struct {
    CARD32 nSubrects;
} rfbRREHeader;

#define sz_rfbRREHeader 4

/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * CoRRE - Compact RRE Encoding.  We have an rfbRREHeader structure giving
 * the number of subrectangles following.  Finally the data follows in the form
 * [<bgpixel><subrect><subrect>...] where each <subrect> is
 * [<pixel><rfbCoRRERectangle>].  This means that
 * the whole rectangle must be at most 255x255 pixels.
 */

typedef struct {
    CARD8 x;
    CARD8 y;
    CARD8 w;
    CARD8 h;
} rfbCoRRERectangle;

#define sz_rfbCoRRERectangle 4

/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * Hextile Encoding.  The rectangle is divided up into "tiles" of 16x16 pixels,
 * starting at the top left going in left-to-right, top-to-bottom order.  If
 * the width of the rectangle is not an exact multiple of 16 then the width of
 * the last tile in each row will be correspondingly smaller.  Similarly if the
 * height is not an exact multiple of 16 then the height of each tile in the
 * final row will also be smaller.  Each tile begins with a "subencoding" type
 * byte, which is a mask made up of a number of bits.  If the Raw bit is set
 * then the other bits are irrelevant; w*h pixel values follow (where w and h
 * are the width and height of the tile).  Otherwise the tile is encoded in a
 * similar way to RRE, except that the position and size of each subrectangle
 * can be specified in just two bytes.  The other bits in the mask are as
 * follows:
 *
 * BackgroundSpecified - if set, a pixel value follows which specifies
 *    the background colour for this tile.  The first non-raw tile in a
 *    rectangle must have this bit set.  If this bit isn't set then the
 *    background is the same as the last tile.
 *
 * ForegroundSpecified - if set, a pixel value follows which specifies
 *    the foreground colour to be used for all subrectangles in this tile.
 *    If this bit is set then the SubrectsColoured bit must be zero.
 *
 * AnySubrects - if set, a single byte follows giving the number of
 *    subrectangles following.  If not set, there are no subrectangles (i.e.
 *    the whole tile is just solid background colour).
 *
 * SubrectsColoured - if set then each subrectangle is preceded by a pixel
 *    value giving the colour of that subrectangle.  If not set, all
 *    subrectangles are the same colour, the foreground colour;  if the
 *    ForegroundSpecified bit wasn't set then the foreground is the same as
 *    the last tile.
 *
 * The position and size of each subrectangle is specified in two bytes.  The
 * Pack macros below can be used to generate the two bytes from x, y, w, h,
 * and the Extract macros can be used to extract the x, y, w, h values from
 * the two bytes.
 */

#define rfbHextileRaw			(1 << 0)
#define rfbHextileBackgroundSpecified	(1 << 1)
#define rfbHextileForegroundSpecified	(1 << 2)
#define rfbHextileAnySubrects		(1 << 3)
#define rfbHextileSubrectsColoured	(1 << 4)

#define rfbHextilePackXY(x,y) (((x) << 4) | (y))
#define rfbHextilePackWH(w,h) ((((w)-1) << 4) | ((h)-1))
#define rfbHextileExtractX(byte) ((byte) >> 4)
#define rfbHextileExtractY(byte) ((byte) & 0xf)
#define rfbHextileExtractW(byte) (((byte) >> 4) + 1)
#define rfbHextileExtractH(byte) (((byte) & 0xf) + 1)

/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 * ZRLE - encoding combining Zlib compression, tiling, palettisation and
 * run-length encoding.
 */

typedef struct {
    CARD32 length;
} rfbZRLEHeader;

#define sz_rfbZRLEHeader 4

#define rfbZRLETileWidth 64
#define rfbZRLETileHeight 64

/*-----------------------------------------------------------------------------
 * SetColourMapEntries - these messages are only sent if the pixel
 * format uses a "colour map" (i.e. trueColour false) and the client has not
 * fixed the entire colour map using FixColourMapEntries.  In addition they
 * will only start being sent after the client has sent its first
 * FramebufferUpdateRequest.  So if the client always tells the server to use
 * trueColour then it never needs to process this type of message.
 */

typedef struct {
    CARD8 type;			/* always rfbSetColourMapEntries */
    CARD8 pad;
    CARD16 firstColour;
    CARD16 nColours;

    /* Followed by nColours * 3 * CARD16
       r1, g1, b1, r2, g2, b2, r3, g3, b3, ..., rn, bn, gn */

} rfbSetColourMapEntriesMsg;

#define sz_rfbSetColourMapEntriesMsg 6

/*-----------------------------------------------------------------------------
 * Bell - ring a bell on the client if it has one.
 */

typedef struct {
    CARD8 type;			/* always rfbBell */
} rfbBellMsg;

#define sz_rfbBellMsg 1

/*-----------------------------------------------------------------------------
 * ServerCutText - the server has new text in its cut buffer.
 */

typedef struct {
    CARD8 type;			/* always rfbServerCutText */
    CARD8 pad1;
    CARD16 pad2;
    CARD32 length;
    /* followed by char text[length] */
} rfbServerCutTextMsg;

#define sz_rfbServerCutTextMsg 8

/*-----------------------------------------------------------------------------
 * ReSizeFrameBuffer - tell the RFB client to alter its framebuffer, either
 * due to a resize of the server desktop or a client-requested scaling factor.
 * The pixel format remains unchanged.
 */

typedef struct {
    CARD8 type;                 /* always rfbReSizeFrameBuffer */
        CARD8 pad1;
        CARD16 desktop_w;       /* Desktop width */
        CARD16 desktop_h;       /* Desktop height */
        CARD16 buffer_w;        /* FrameBuffer width */
        CARD16 buffer_h;        /* Framebuffer height */
    CARD16 pad2;

} rfbReSizeFrameBufferMsg;

#define sz_rfbReSizeFrameBufferMsg (12)

/*-----------------------------------------------------------------------------
 * Union of all server->client messages.
 */

typedef union {
    CARD8 type;
    rfbFramebufferUpdateMsg fu;
    rfbSetColourMapEntriesMsg scme;
    rfbBellMsg b;
    rfbServerCutTextMsg sct;
    rfbReSizeFrameBufferMsg rsfb;
} rfbServerToClientMsg;

/*****************************************************************************
 *
 * Message definitions (client -> server)
 *
 *****************************************************************************/

/*-----------------------------------------------------------------------------
 * SetPixelFormat - tell the RFB server the format in which the client wants
 * pixels sent.
 */

typedef struct {
    CARD8 type;			/* always rfbSetPixelFormat */
    CARD8 pad1;
    CARD16 pad2;
    rfbPixelFormat format;
} rfbSetPixelFormatMsg;

#define sz_rfbSetPixelFormatMsg (sz_rfbPixelFormat + 4)

/*-----------------------------------------------------------------------------
 * FixColourMapEntries - when the pixel format uses a "colour map", fix
 * read-only colour map entries.
 *
 *    ***************** NOT CURRENTLY SUPPORTED *****************
 */

typedef struct {
    CARD8 type;			/* always rfbFixColourMapEntries */
    CARD8 pad;
    CARD16 firstColour;
    CARD16 nColours;

    /* Followed by nColours * 3 * CARD16
       r1, g1, b1, r2, g2, b2, r3, g3, b3, ..., rn, bn, gn */

} rfbFixColourMapEntriesMsg;

#define sz_rfbFixColourMapEntriesMsg 6

/*-----------------------------------------------------------------------------
 * SetEncodings - tell the RFB server which encoding types we accept.  Put them
 * in order of preference, if we have any.  We may always receive raw
 * encoding, even if we don't specify it here.
 */

typedef struct {
    CARD8 type;			/* always rfbSetEncodings */
    CARD8 pad;
    CARD16 nEncodings;
    /* followed by nEncodings * CARD32 encoding types */
} rfbSetEncodingsMsg;

#define sz_rfbSetEncodingsMsg 4

/*-----------------------------------------------------------------------------
 * SetScaleFactor - tell the RFB server to alter the scale factor for the
 * client buffer.
 */

typedef struct {
	CARD8 type;                 /* always rfbSetScaleFactor */
	CARD8 scale;                /* Scale factor (positive non-zero integer) */
	CARD16 pad2;
} rfbSetScaleFactorMsg;

#define sz_rfbSetScaleFactorMsg (4)

/*-----------------------------------------------------------------------------
 * FramebufferUpdateRequest - request for a framebuffer update.  If incremental
 * is true then the client just wants the changes since the last update.  If
 * false then it wants the whole of the specified rectangle.
 */

typedef struct {
    CARD8 type;			/* always rfbFramebufferUpdateRequest */
    CARD8 incremental;
    CARD16 x;
    CARD16 y;
    CARD16 w;
    CARD16 h;
} rfbFramebufferUpdateRequestMsg;

#define sz_rfbFramebufferUpdateRequestMsg 10

/*-----------------------------------------------------------------------------
 * KeyEvent - key press or release
 *
 * Keys are specified using the "keysym" values defined by the X Window System.
 * For most ordinary keys, the keysym is the same as the corresponding ASCII
 * value.  Other common keys are:
 *
 * BackSpace		0xff08
 * Tab			0xff09
 * Return or Enter	0xff0d
 * Escape		0xff1b
 * Insert		0xff63
 * Delete		0xffff
 * Home			0xff50
 * End			0xff57
 * Page Up		0xff55
 * Page Down		0xff56
 * Left			0xff51
 * Up			0xff52
 * Right		0xff53
 * Down			0xff54
 * F1			0xffbe
 * F2			0xffbf
 * ...			...
 * F12			0xffc9
 * Shift		0xffe1
 * Control		0xffe3
 * Meta			0xffe7
 * Alt			0xffe9
 */

typedef struct {
    CARD8 type;			/* always rfbKeyEvent */
    CARD8 down;			/* true if down (press), false if up */
    CARD16 pad;
    CARD32 key;			/* key is specified as an X keysym */
} rfbKeyEventMsg;

#define sz_rfbKeyEventMsg 8

/*-----------------------------------------------------------------------------
 * PointerEvent - mouse/pen move and/or button press.
 */

typedef struct {
    CARD8 type;			/* always rfbPointerEvent */
    CARD8 buttonMask;		/* bits 0-7 are buttons 1-8, 0=up, 1=down */
    CARD16 x;
    CARD16 y;
} rfbPointerEventMsg;

#define rfbButton1Mask 1
#define rfbButton2Mask 2
#define rfbButton3Mask 4
#define rfbButton4Mask 8
#define rfbButton5Mask 16
#define rfbWheelUpMask rfbButton4Mask
#define rfbWheelDownMask rfbButton5Mask

#define sz_rfbPointerEventMsg 6

/*-----------------------------------------------------------------------------
 * ClientCutText - the client has new text in its cut buffer.
 */

typedef struct {
    CARD8 type;			/* always rfbClientCutText */
    CARD8 pad1;
    CARD16 pad2;
    CARD32 length;
    /* followed by char text[length] */
} rfbClientCutTextMsg;

#define sz_rfbClientCutTextMsg 8

/*-----------------------------------------------------------------------------
 * Union of all client->server messages.
 */

typedef union {
    CARD8 type;
    rfbSetPixelFormatMsg spf;
    rfbSetScaleFactorMsg ssf;
    rfbFixColourMapEntriesMsg fcme;
    rfbSetEncodingsMsg se;
    rfbFramebufferUpdateRequestMsg fur;
    rfbKeyEventMsg ke;
    rfbPointerEventMsg pe;
    rfbClientCutTextMsg cct;
} rfbClientToServerMsg;


text:
using System;

namespace Lucene.Net.Support
{

    public static class MathExtensions
    {
        /// <summary>
        /// Converts an angle measured in degrees to an approximately equivalent angle
        /// measured in radians. The conversion from degrees to radians is generally inexact.
        /// </summary>
        /// <param name="degrees">An angle in degrees to convert to radians</param>
        /// <returns>The value in radians</returns>
        public static double ToRadians(this double degrees)
        {
            return degrees / 180 * Math.PI;
        }

        /// <summary>
        /// Converts an angle measured in degrees to an approximately equivalent angle
        /// measured in radians. The conversion from degrees to radians is generally inexact.
        /// </summary>
        /// <param name="degrees">An angle in degrees to convert to radians</param>
        /// <returns>The value in radians</returns>
        public static decimal ToRadians(this decimal degrees)
        {
            return degrees / (decimal)(180 * Math.PI);
        }

        /// <summary>
        /// Converts an angle measured in degrees to an approximately equivalent angle
        /// measured in radians. The conversion from degrees to radians is generally inexact.
        /// </summary>
        /// <param name="degrees">An angle in degrees to convert to radians</param>
        /// <returns>The value in radians</returns>
        public static double ToRadians(this int degrees)
        {
            return ((double)degrees) / 180 * Math.PI;
        }

        /// <summary>
        /// Converts an angle measured in radians to an approximately equivalent angle
        /// measured in degrees. The conversion from radians to degrees is generally
        /// inexact; users should not expect Cos((90.0).ToRadians()) to exactly equal 0.0.
        /// </summary>
        /// <param name="radians">An angle in radians to convert to radians</param>
        /// <returns>The value in radians</returns>
        public static double ToDegrees(this double radians)
        {
            return radians * 180 / Math.PI;
        }

        /// <summary>
        /// Converts an angle measured in radians to an approximately equivalent angle
        /// measured in degrees. The conversion from radians to degrees is generally
        /// inexact; users should not expect Cos((90.0).ToRadians()) to exactly equal 0.0.
        /// </summary>
        /// <param name="radians">An angle in radians to convert to radians</param>
        /// <returns>The value in radians</returns>
        public static decimal ToDegrees(this decimal radians)
        {
            return radians * 180 / (decimal)Math.PI;
        }

        /// <summary>
        /// Converts an angle measured in radians to an approximately equivalent angle
        /// measured in degrees. The conversion from radians to degrees is generally
        /// inexact; users should not expect Cos((90.0).ToRadians()) to exactly equal 0.0.
        /// </summary>
        /// <param name="radians">An angle in radians to convert to radians</param>
        /// <returns>The value in radians</returns>
        public static double ToDegrees(this int radians)
        {
            return ((double)radians) * 180 / Math.PI;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
--
-- Tables for information about students and their academic progress.
--

USE `njala_proto`;

-- Drop triggers, functions, and procedures referring to tables defined
-- in this file.

DROP TRIGGER IF EXISTS CloseApplicant_Insert;
DROP TRIGGER IF EXISTS CloseApplicant_Update;

DROP TRIGGER IF EXISTS SAPstatusAndDateCheck_insert;
DROP TRIGGER IF EXISTS SAPstatusAndDateCheck_update;

DROP TRIGGER IF EXISTS CreateEnrollmentGradeRecord;

DROP TRIGGER IF EXISTS EndEnrollmentChangesStatus_Insert;
DROP TRIGGER IF EXISTS EndEnrollmentChangesStatus_Update;

DROP TRIGGER IF EXISTS AuthorizeGrade_insert;
DROP TRIGGER IF EXISTS AuthorizeGrade_update;

DROP FUNCTION IF EXISTS TermCensusDate;
DROP FUNCTION IF EXISTS ModOfferingEndDate;
DROP FUNCTION IF EXISTS TermCensusDate;
DROP FUNCTION IF EXISTS CalcCumHrs;
DROP FUNCTION IF EXISTS CalcCumPts;
DROP FUNCTION IF EXISTS GradePts;

DROP PROCEDURE IF EXISTS CancelStudentReg;
DROP PROCEDURE IF EXISTS UpdateSessionStanding;
DROP PROCEDURE IF EXISTS UpdateAllSessionStandings;

-- Before dropping Student, need to drop table(s) that depend on it.
SOURCE dropSmartStudentDependencies.sql;

-- Drop other tables defined in this file.

DROP TABLE IF EXISTS AdmissTestCodes;
DROP TABLE IF EXISTS AdmissTestDescriptors;
DROP TABLE IF EXISTS AdmissExamNames;
DROP TABLE IF EXISTS ApplicationStatusCodes;
DROP TABLE IF EXISTS AdvisorTypes;
DROP TABLE IF EXISTS StudentProgramStatusCodes;
DROP TABLE IF EXISTS ClassLevelCodes;
DROP TABLE IF EXISTS StudentLeaveTypes;
DROP TABLE IF EXISTS AnnotationTypes;
DROP TABLE IF EXISTS AnnotationAuthorities;
DROP TABLE IF EXISTS StudentModStatusCodes;
DROP TABLE IF EXISTS TermStandingCodes;

DROP TABLE IF EXISTS Applicant;
DROP TABLE IF EXISTS Student;

CREATE Table AdmissTestCodes (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    testCode VARCHAR ( 20 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO AdmissTestCodes (testCode) VALUES
('Entrance Exam')
, ('WASSCE')
, ('GCE O')
, ('GCE A')
, ('OTHER')
;

CREATE Table AdmissTestDescriptors (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    descriptor VARCHAR ( 20 ),
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO AdmissTestDescriptors (descriptor) VALUES
(NULL)
, ('GOVT.')
, ('PR.')
, ('GOVT./PR.')
, ('PR./GOVT.')
;

CREATE Table AdmissExamNames (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    examName VARCHAR ( 20 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO AdmissExamNames (examName) VALUES
('AGRIC. SCIENCE')
, ('B. MGMT.')
, ('BIOLOGY')
, ('COMMERCE')
, ('COST ACCOUNTS')
, ('ECONOMICS')
, ('ENGLISH')
, ('ENGLISH LIT')
, ('FIN. ACCOUNTS')
, ('FRENCH')
, ('GEOGRAPHY')
, ('HEALTH SC.')
, ('MATHS')
, ('FUR. MATHS')
, ('STATISTICS')
, ('OTHER')
;

CREATE TABLE ApplicationStatusCodes (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    statusCode VARCHAR ( 15 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO ApplicationStatusCodes (statusCode) VALUES
('Pending')
, ('Accepted')
, ('WaitList')
, ('Rejected')
;

CREATE TABLE AdvisorTypes (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    advisorType VARCHAR ( 20 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO AdvisorTypes (advisorType) VALUES
('Primary')
, ('Secondary')
;

CREATE TABLE StudentProgramStatusCodes (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    pgmStatusCode VARCHAR ( 20 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO StudentProgramStatusCodes (pgmStatusCode) VALUES
('Preparatory')
, ('Active')
, ('Withdrawn')
, ('Ended')
, ('Completed')
;

CREATE TABLE ClassLevelCodes (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    classLevelCode VARCHAR ( 10 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO ClassLevelCodes (classLevelCode) VALUES
('1st Yr')
, ('2nd Yr')
, ('3rd Yr')
, ('4th Yr')
, ('5th Yr')
, ('Longterm')
;

CREATE TABLE StudentLeaveTypes (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    studentLeaveCode VARCHAR ( 20 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO StudentLeaveTypes (studentLeaveCode) VALUES
('Withdrawn')
, ('Medical Leave')
, ('Study Away')
, ('Suspended')
, ('Expelled')
, ('Dismissed')
;

CREATE TABLE AnnotationTypes (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    annotationCode VARCHAR ( 20 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO AnnotationTypes (annotationCode) VALUES
('Achievement')
, ('Policy Exception')
, ('TranscriptRemark')
, ('Disciplinary')
, ('Suspended')
, ('Expelled')
, ('Dismissed')
;

CREATE TABLE AnnotationAuthorities (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    authCode VARCHAR ( 20 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO AnnotationAuthorities (authCode) VALUES
('Dean')
, ('Registrar')
, ('Advisor')
, ('Vice Chancellor')
;

CREATE TABLE StudentModStatusCodes (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    modStatusCode VARCHAR ( 10 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO StudentModStatusCodes (modStatusCode) VALUES
('Enrolled')
-- , ('Dropped')
, ('Withdrawn')
, ('Completed')
, ('Canceled')
;

CREATE Table TermStandingCodes (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    termStandingCode VARCHAR ( 20 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO TermStandingCodes (termStandingCode) VALUES
('GOOD')
, ("DEAN'S LIST")
, ('PROBATION')
, ('FINAL PROBATION')
, ('OTHER')
;

CREATE TABLE Applicant (
    personID INT NOT NULL PRIMARY KEY ,
    primaryLanguage VARCHAR ( 20 ),
    chosenProgramID INT NOT NULL,
    secondaryProgramID INT,
    previousApplYears VARCHAR ( 40 ),
    applyingElsewhere VARCHAR ( 150 ),
    extraCurrics VARCHAR ( 150 ),
    interviewLoc VARCHAR ( 20 ),
    hodApproval VARCHAR ( 15 ) NOT NULL DEFAULT 'Pending',
    deanApproval VARCHAR ( 15 ) NOT NULL DEFAULT 'Pending',
    deanRemarks VARCHAR ( 75 ),
    aaApproval VARCHAR ( 15 ) NOT NULL DEFAULT 'Pending',
    status VARCHAR ( 15 ) NOT NULL DEFAULT 'Pending',
    received DATE DEFAULT NULL,
    closed DATE DEFAULT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (personID) REFERENCES Person (personID) ON UPDATE CASCADE
);

DELIMITER //
CREATE TRIGGER CloseApplicant_Insert BEFORE INSERT ON Applicant
  FOR EACH ROW BEGIN
    SET NEW.received = IF ( ( isNull(NEW.received) AND NEW.status = 'Pending' ),
                     NOW(), NEW.received);
    SET NEW.closed = IF ( (NEW.status = 'Accepted' OR NEW.status = 'Denied')
                          AND NEW.closed IS NULL,
                     NOW(), NEW.closed);
  END; //
CREATE TRIGGER CloseApplicant_Update BEFORE UPDATE ON Applicant
  FOR EACH ROW BEGIN
    SET NEW.closed = IF ( (NEW.status = 'Accepted' OR NEW.status = 'Denied')
                          AND NEW.closed IS NULL,
                     NOW(), NEW.closed);
  END; //
DELIMITER ;

CREATE TABLE Student (
    studentID INT NOT NULL AUTO_INCREMENT PRIMARY Key,
    personID INT NOT NULL,
    advisorID INT NULL DEFAULT NULL,
    campusAddress VARCHAR ( 20 ),
    primaryLanguage VARCHAR ( 20 ),
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (personID) REFERENCES Person (personID) ON UPDATE CASCADE,
    FOREIGN KEY (advisorID) REFERENCES Person (personID) ON DELETE SET NULL
        ON UPDATE CASCADE,
    UNIQUE(personID),
    INDEX (advisorID)
);

CREATE TABLE AdmissExams (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    personID INT NOT NULL,
    date_taken DATE,
    type VARCHAR ( 15 ) NOT NULL,
    qualifier VARCHAR ( 15 ),
    examName VARCHAR ( 15 ) NOT NULL,
    score VARCHAR ( 5 ) NOT NULL,
    percentile INT,
    equivalency VARCHAR ( 50 ),
    comments VARCHAR ( 100 ),
    FOREIGN KEY (personID) REFERENCES Person (personID)
);

CREATE TABLE Advising (
    adviseeID INT NOT NULL,
    advisorID INT NOT NULL,
    advisorType VARCHAR ( 20 ) NOT NULL,
    startDate DATE NOT NULL,
    endDate DATE,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (adviseeID, advisorID, startDate),
    FOREIGN KEY (adviseeID) REFERENCES Student (studentID),
    FOREIGN KEY (advisorID) REFERENCES Person (personID)
);

-- Initialize title, type, dept, and college from AcadProgram (keep a
-- historical copy here in case any of those change in the future).

CREATE TABLE StudentAcadProgram (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    studentID INT NOT NULL,
    programID INT NOT NULL,
    title VARCHAR ( 100 ) NOT NULL,
    shortTitle VARCHAR ( 38 ) NOT NULL,
    type VARCHAR ( 15 ) NOT NULL DEFAULT 'Coursework',
    schoolCode VARCHAR ( 8 ) DEFAULT NULL,
    deptCode VARCHAR ( 8 ) DEFAULT NULL,
    -- requirementSet INT NOT NULL,
    parentProgramID INT NULL,
    status VARCHAR ( 20 ) NOT NULL,
    prepStartDate DATE NOT NULL,
    startDate DATE NOT NULL,
    anticipatedCompletionDate DATE,
    completionDate DATE,
    endDate DATE,
    classLevel VARCHAR ( 10 ) NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (studentID) REFERENCES Student (studentID),
    FOREIGN KEY (parentProgramID) REFERENCES StudentAcadProgram (pk_id)
        ON UPDATE CASCADE ON DELETE RESTRICT
);

DELIMITER //
CREATE TRIGGER SAPstatusAndDateCheck_insert BEFORE INSERT ON StudentAcadProgram
  FOR EACH ROW BEGIN
    SET NEW.status = IF (NEW.completionDate IS NOT NULL AND
                         NEW.completionDate <> 0, 'Completed',
                        IF (NEW.status = 'Ended', 'Ended',
                        IF (NEW.endDate IS NOT NULL AND
                         NEW.endDate <> 0, 'Withdrawn',
                        IF (NOW() > NEW.startDate, 'Active', NEW.status))));
    SET NEW.endDate = IF (NEW.completionDate IS NOT NULL,
                                NEW.completionDate, NEW.endDate);
  END; //
CREATE TRIGGER SAPstatusAndDateCheck_update BEFORE UPDATE ON StudentAcadProgram
  FOR EACH ROW BEGIN
    SET NEW.status = IF (NEW.completionDate IS NOT NULL AND
                         NEW.completionDate <> 0, 'Completed',
                        IF (NEW.status = 'Ended', 'Ended',
                        IF (NEW.endDate IS NOT NULL AND
                         NEW.endDate <> 0, 'Withdrawn',
                        IF (NOW() > NEW.startDate, 'Active', NEW.status))));
    SET NEW.endDate = IF (NEW.completionDate IS NOT NULL,
                                NEW.completionDate, NEW.endDate);
  END; //
DELIMITER ;

# /*
# CAREFUL!!!  If a parent program ID is provided, then student ID
# is redundant; have to be careful to keep these two things synchronized.
# (Also anticipated completion date and class year, at least at K.)
# */

# /*
# Initialize program title and type from AcadProgram.
# Initialize requirement set from ProgramRequirements table.
# Important to specify both title and requirement set here, because
# majors can change names and requirements.
# Initialize school, division, and department from AcadProgram?
# (Do we really need to
# capture school, division, and department here?  Do we need a record of
# what they were when the student was enrolled in the program? Or can
# we just import them from the current program information with a join?)
# */

# /*
# Is there any chance that a student might be following a program
# that is being used to satisfy multiple parent programs?  E.g., a
# major or minor counting towards a degree and a certificate?  If so,
# need to drop parentProgramID field and either make StudentAcadProgram
# be a container class, or create a program/subprogram relationship
# table.
# */

# /*
# There should be a requirement set defined for every program.
# Programs could be: a course of study, a degree, a major, a minor
# A student might be signed up for multiple independent programs and maybe
# degrees or credential can be awarded as each program is finished.
# A student can also be signed up for one or more programs that
# serve as sub-programs for an over-arching program, e.g., the K undergrad
# program requires a general education and a major, and could also
# have other sub-programs, such as additional major(s), minor(s).
# */

CREATE TABLE StudentLeaves (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    studentID INT NOT NULL,
    type VARCHAR ( 20 ) NOT NULL,
    comment VARCHAR ( 100 ) NOT NULL,
    startDate DATE NOT NULL,
    anticipatedEndDate DATE,
    endDate DATE,
    prepStartDate DATE,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (studentID) REFERENCES Student (studentID)
);

CREATE TABLE StudentAnnotations (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    studentID INT NOT NULL,
    authority VARCHAR ( 20 ) NOT NULL,
    annotationType VARCHAR ( 20 ) NOT NULL,
    annotation VARCHAR ( 100 ) NOT NULL,
    enteredBy VARCHAR ( 20 ) NOT NULL,
    date DATE NOT NULL,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (studentID) REFERENCES Student (studentID)
);

CREATE TABLE Enrollment (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    studentID INT NOT NULL,
    modOfferingID INT NOT NULL,
    status VARCHAR ( 10 ) NOT NULL DEFAULT 'Enrolled',
    registDate DATE NOT NULL,
    endDate DATE,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (studentID) REFERENCES Student (studentID),
    FOREIGN KEY (modOfferingID) REFERENCES ModuleOfferings (pk_id),
    INDEX (studentID),
    INDEX (modOfferingID)
);

CREATE TABLE CourseGrades (
    enrollmentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    continuousAssessment INT,
    examScore INT,
    calcFinalGrade VARCHAR ( 5 ),
--    continuousAssessment VARCHAR ( 3 ),
--    examScore VARCHAR ( 3 ),
--    submittedTermGrade VARCHAR ( 3 ),
    approved ENUM('F', 'T') NOT NULL DEFAULT 'F',
    authority VARCHAR ( 20 ),
--    authority VARCHAR ( 20 ) NOT NULL,
    transcriptGrade VARCHAR ( 5 ),
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (enrollmentID) REFERENCES Enrollment (pk_id),
    INDEX (enrollmentID)
);

/*
CREATE TABLE GradeApproval (
    enrollmentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (enrollmentID) REFERENCES Enrollment (pk_id),
    INDEX (enrollmentID)
);
*/

DELIMITER //

CREATE FUNCTION TermCensusDate(inOffering INT)
RETURNS DATE DETERMINISTIC
COMMENT "Returns the census date for the module offering's term"
BEGIN
DECLARE
    retValue  DATE;
BEGIN
    SELECT term INTO @modTerm FROM ModuleOfferings WHERE `pk_id` = inOffering;
    SELECT censusDate INTO retValue FROM Terms WHERE `term` = @modTerm;
    RETURN retValue;
END;
END; //

CREATE FUNCTION ModOfferingEndDate(inOffering INT)
RETURNS DATE DETERMINISTIC
COMMENT 'Returns the end date for the specified offering'
BEGIN
DECLARE
    modOffEndDate  DATE;
BEGIN
    SELECT endDate INTO modOffEndDate FROM ModuleOfferings
        WHERE `pk_id` = inOffering;
    RETURN modOffEndDate;
END;
END; //

DELIMITER ;

DELIMITER //

CREATE TRIGGER CreateEnrollmentGradeRecord AFTER INSERT ON Enrollment
  FOR EACH ROW BEGIN
    INSERT INTO `CourseGrades` (enrollmentID)
    VALUES (NEW.pk_id);
  END; //

CREATE TRIGGER EndEnrollmentChangesStatus_Insert BEFORE INSERT ON Enrollment
  FOR EACH ROW BEGIN
    SET NEW.status =
        IF ( NEW.status = 'Enrolled',
            IF ( NEW.endDate IS NOT NULL AND NEW.endDate <> 0,
                IF (NEW.endDate < TermCensusDate(NEW.modOfferingID),
                    'Dropped',  -- End date is before census date
                    IF (NEW.endDate < ModOfferingEndDate(NEW.modOfferingID),
                        'Withdrawn',    -- End date is before module end date
                        'Completed')),  -- End date is same or after mod end
                'Enrolled'),    -- End date is NULL or 0
            NEW.status);    -- Status is not 'Enrolled'
  END; //
CREATE TRIGGER EndEnrollmentChangesStatus_Update BEFORE UPDATE ON Enrollment
  FOR EACH ROW BEGIN
    SET NEW.status =
        IF ( NEW.status = 'Enrolled',
            IF ( NEW.endDate IS NOT NULL AND NEW.endDate <> 0,
                IF (NEW.endDate < TermCensusDate(NEW.modOfferingID),
                    'Dropped',  -- End date is before census date
                    IF (NEW.endDate < ModOfferingEndDate(NEW.modOfferingID),
                        'Withdrawn',    -- End date is before module end date
                        'Completed')),  -- End date is same or after mod end
                'Enrolled'),    -- End date is NULL or 0
            NEW.status);    -- Status is not 'Enrolled'
  END; //

CREATE TRIGGER GradeEndsEnrollment_Update AFTER UPDATE ON CourseGrades
  FOR EACH ROW BEGIN
    UPDATE Enrollment SET endDate =
                IF (NEW.calcFinalGrade IS NOT NULL AND endDate IS NULL,
                    NOW(), endDate)
        WHERE pk_id = NEW.enrollmentID;
  END; //

DELIMITER ;

DELIMITER //
CREATE TRIGGER AuthorizeGrade_insert BEFORE INSERT ON CourseGrades
  FOR EACH ROW BEGIN
    SET NEW.transcriptGrade = IF (NEW.approved = 'T' AND
                                  NEW.transcriptGrade IS NULL,
                               NEW.calcFinalGrade,
                               NEW.transcriptGrade);
  END; //
CREATE TRIGGER AuthorizeGrade_update BEFORE UPDATE ON CourseGrades
  FOR EACH ROW BEGIN
    SET NEW.transcriptGrade = IF (NEW.approved = 'T' AND
                                  NEW.transcriptGrade IS NULL,
                               NEW.calcFinalGrade,
                               NEW.transcriptGrade);
  END; //
DELIMITER ;

/*  NOT TESTED YET !!!
DELIMITER //
CREATE PROCEDURE CancelStudentReg (IN inTerm VARCHAR(10),
                                   IN inModuleID INT, IN inSection VARCHAR(3))
COMMENT 'Cancels the registration for every student enrolled in the
specified module offering'
BEGIN
    UPDATE Enrollment SET status = 'Cancelled', endDate = NOW()
        WHERE term = inTerm AND moduleID = inModuleID AND section = inSection
        AND status = 'Enrolled';
END; //

DELIMITER ;
*/

# /* Status:  (Note: status is dependant on module offering dates/status.)
# If offering status is canceled and end date is offering end date: Canceled.
#   (trigger on module offering: if offering canceled, cancel student reg)
# If end date not null and before offering's: Dropped.
# If end date not null and before offering's end date: Withdrawn.
# If end date not null and equal to (or after) offering's end date: Completed.
# Else: Enrolled.
# */

CREATE TABLE CompExamScores (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    studentID INT NOT NULL,
    examName VARCHAR ( 30 ) NOT NULL,
    date_taken DATE DEFAULT NULL,
    grade VARCHAR ( 3 ) NOT NULL,
    FOREIGN KEY (studentID) REFERENCES Student (studentID)
);

CREATE TABLE TermStanding (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    studentID INT NOT NULL,
    term VARCHAR( 15 ) NOT NULL,
    standing VARCHAR ( 20 ) NOT NULL DEFAULT 'GOOD',
    creditsAttempted DOUBLE,
    creditsEarned DOUBLE,
    termGPA DECIMAL(6,3),
    cumulativeCreditsAttempted DOUBLE,
    cumulativeCreditsEarned DOUBLE,
    cumulativeGPA DECIMAL(6,3),
    comment VARCHAR ( 100 ),
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (studentID) REFERENCES Student (studentID),
    INDEX (studentID),
    INDEX (term),
    INDEX (standing)
);

CREATE TABLE SessionStanding (
    pk_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    studentID INT NOT NULL,
    acadYear VARCHAR( 10 ),
    sessionTotalHrs INT,
    sessionTotalPts INT,
    sessionGPA DECIMAL(6,3),
    cumTotalHrs INT,
    cumTotalPts INT,
    cumGPA DECIMAL(6,3),
    standing VARCHAR ( 20 ) NOT NULL DEFAULT 'GOOD',
    comment VARCHAR ( 100 ),
    updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
        ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (studentID) REFERENCES Student (studentID),
    INDEX (studentID),
    INDEX (acadYear),
    INDEX (standing)
);

DELIMITER //
CREATE FUNCTION CalcCumHrs(id INT)
RETURNS INT DETERMINISTIC
COMMENT "Computes the cumulative hours earned by the given student"
BEGIN
    SELECT SUM(sessionTotalHrs) INTO @cumHrs FROM SessionStanding
        WHERE studentID = id;
    RETURN IF (isNull(@cumHrs), 0, @cumHrs);
END; //
DELIMITER ;

DELIMITER //
CREATE FUNCTION CalcCumPts(id INT)
RETURNS INT DETERMINISTIC
COMMENT "Computes the cumulative points earned by the given student"
BEGIN
    SELECT SUM(sessionTotalPts) INTO @cumPts FROM SessionStanding
        WHERE studentID = id;
    RETURN IF (isNull(@cumPts), 0, @cumPts);
END; //
DELIMITER ;

DELIMITER //
CREATE FUNCTION GradePts(grade VARCHAR ( 5 ), hrs INT)
RETURNS INT DETERMINISTIC
COMMENT "Computes the points earned for the given grade (grade * hrs)"
BEGIN
    RETURN hrs *
            ( CASE grade WHEN 'A' THEN 5 WHEN 'B' THEN 4
                         WHEN 'C' THEN 3 WHEN 'D' THEN 2
                         WHEN 'D' THEN 1 ELSE 0 END );
END; //
DELIMITER ;

DELIMITER //
-- should use transcriptGrade, not calcFinalGrade
CREATE Procedure UpdateSessionStanding(in stuID INT, in sessID INT,
                                       in acadYear VARCHAR(10))
COMMENT "Calculates the latest session GPA and cumulative values for this student"
BEGIN
    -- Do calculations.
    SELECT SUM(ModuleOfferings.creditHours),
           SUM(GradePts(CourseGrades.calcFinalGrade,
                        ModuleOfferings.creditHours))
        INTO @totalHrs, @totalPts
        FROM CourseGrades
        LEFT JOIN Enrollment
                ON CourseGrades.enrollmentID = Enrollment.pk_id
        LEFT JOIN ModuleOfferings
                ON Enrollment.modOfferingID=ModuleOfferings.pk_id
        LEFT JOIN Terms ON ModuleOfferings.term = Terms.term
        WHERE Enrollment.studentID=stuID AND Terms.acadYear=acadYear;
    SET @sessGPA = IF ( ( NOT isNULL(@totalHrs) AND @totalHrs <> 0 ),
                        (@totalPts / @totalHrs), 0);
    SET @newCumHrs = CalcCumHrs(stuID) + @totalHrs;
    SET @newCumPts = CalcCumPts(stuID) + @totalPts;
    SET @cumGPA = IF ( ( NOT isNULL(@newCumHrs) AND @newCumHrs <> 0 ),
                        (@newCumPts / @newCumHrs), 0);

    -- Do update..
    UPDATE SessionStanding SET sessionTotalHrs = @totalHrs,
                               sessionTotalPts = @totalPts,
                               sessionGPA = @sessGPA,
                               cumTotalHrs = @newCumHrs,
                               cumTotalPts = @newCumPts,
                               cumGPA = @cumGPA
        WHERE pk_id = sessID;
END; //
DELIMITER ;

DELIMITER //
CREATE PROCEDURE UpdateAllSessionStandings (IN inAcadYear VARCHAR(10))
COMMENT 'Updates student session standings for the given acad. year'
BEGIN
    DECLARE student_id INT;
    DECLARE sess_id INT;
    DECLARE done INT DEFAULT FALSE;
    DECLARE cur CURSOR FOR SELECT Student.studentID,
                                  SessionStanding.pk_id
        FROM Student LEFT JOIN SessionStanding
          ON Student.studentID = SessionStanding.studentID
         AND SessionStanding.acadYear = inAcadYear;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    OPEN cur;
        read_loop: LOOP
            FETCH cur INTO student_id, sess_id;
            IF done THEN
              LEAVE read_loop;
            END IF;
            CALL UpdateSessionStanding(student_id, sess_id, inAcadYear);
        END LOOP;
    CLOSE cur;
END; //
DELIMITER ;


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-people/photographers/hales-chance-b" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/photographers/hales-chance-b</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Hales, Chance B.</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/photographers/hales-chance-b</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-people/photographers/hales-chance-b</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using sien.entityframework;
using sien.models;
using sien.helpers;
using System.Web.Mvc;

namespace sien.dao
{
    public class EscolaDao : BaseDao
    {
        public List<Instituicao> listagem()
        {
            return dbContext.Instituicao.ToList().Select(s => new Instituicao()
            {
                id = s.id,
                nome = s.nome,
                cnpj = s.cnpj
            }).ToList();
        }

        public CadastroEscola carregaEscola(int idEscola)
        {
            Instituicao inst = dbContext.Instituicao.Include("Cidade").FirstOrDefault(f => f.id == idEscola);
            CadastroEscola obj;
            int idEstado = (inst != null && inst.Cidade != null ? inst.Cidade.idEstado : 0);

            if (inst != null)
            {

                obj = new CadastroEscola()
                {
                    escola = new Escola()
                    {
                        id = inst.id,
                        nome = inst.nome,
                        idCidade = inst.idCidade,
                        idEstado = inst.Cidade != null ? inst.Cidade.idEstado : 0,
                        endereco = inst.endereco,
                        cnpj = inst.cnpj
                    },
                    estados = dbContext.Estado.
                        Select(s => new Dropdownlist() { id = s.id, nome = s.nome }).ToList(),

                    cidades = dbContext.Cidade.
                        Where(w => w.idEstado == idEstado).
                        Select(s => new Dropdownlist() { id = s.id, nome = s.nome }).ToList(),

                    colaboradores = dbContext.Usuario.
                        Where(w => w.webpages_Roles.FirstOrDefault().RoleId == (int)Perfil.Diretor ||
                                   w.webpages_Roles.FirstOrDefault().RoleId == (int)Perfil.Secretario ||
                                   w.webpages_Roles.FirstOrDefault().RoleId == (int)Perfil.Professor).
                        Except(dbContext.InstituicaoColaborador.Where(w => w.idInstituicao == idEscola).Select(s => s.Usuario)).
                        OrderBy(o => o.nome).ToList().
                        Select(s => new Dropdownlist()
                        {

                            id = s.id,
                            nome = string.Concat(s.nome, " - ", s.webpages_Roles.FirstOrDefault().RoleName)
                        }).ToList()
                };
            }
            else
            {
                obj = new CadastroEscola()
                {
                    escola = new Escola()
                    {
                        nome = string.Empty,
                        idCidade = 0,
                        idEstado = 0,
                        endereco = string.Empty,
                        cnpj = string.Empty
                    },
                    estados = dbContext.Estado.
                        Select(s => new Dropdownlist() { id = s.id, nome = s.nome }).ToList(),

                    cidades = new List<Dropdownlist>(),

                    colaboradores = dbContext.webpages_Roles.
                        FirstOrDefault(w => w.RoleId == (int)Perfil.Administrador).
                        Usuario.Select(s => new Dropdownlist() { id = s.id, nome = s.nome }).ToList()
                };
            }
            return obj;
        }

        public List<Dropdownlist> carregaCidade(int idEstado)
        {
            return dbContext.Cidade.Where(w => w.idEstado == idEstado).
                Select(s => new Dropdownlist() { id = s.id, nome = s.nome }).ToList();
        }

        public Mensagem salvarEscola(Instituicao escola)
        {
            try
            {
                dbContext.sp_InsertUpdateInstituicao(escola.id, escola.nome, escola.idCidade, escola.endereco, escola.cnpj);
                return new Mensagem(true, "Escola salva com sucesso!");
            }
            catch (Exception)
            {
                return new Mensagem(false, "Ocorreu um erro ao salvar a Escola!");
            }
        }

        public Mensagem excluirEscola(int idEscola)
        {
            try
            {
                dbContext.sp_DeleteInstituicao(idEscola);
                return new Mensagem(true, "Escola excluída com sucesso!");
            }
            catch (Exception)
            {
                return new Mensagem(false, "Ocorreu um erro ao excluir a Escola!");
            }
        }

        public List<GridDefault> listagemColaboradores(int idInstituicao)
        {
            return dbContext.InstituicaoColaborador.
                Where(w => w.idInstituicao == idInstituicao).ToList().
                Select(s => new GridDefault()
                {
                    id = s.id,
                    nome = string.Concat(s.Usuario.nome, " - ", s.Usuario.webpages_Roles.FirstOrDefault().RoleName)
                }).ToList();
        }

        public Mensagem inserirColaborador(int idInstituicao, int idColaborador)
        {
            try
            {
                dbContext.sp_InsertInstituicaoColaborador(idInstituicao, idColaborador);
                return new Mensagem(true, "Colaborador inserido com sucesso!");
            }
            catch (Exception)
            {
                return new Mensagem(false, "Ocorreu um erro ao inserir o colaborador!");
            }
        }

        public Mensagem excluirColaborador(int id)
        {
            try
            {
                dbContext.sp_DeleteInstituicaoColaborador(id);
                return new Mensagem(true, "Colaborador excluído com sucesso!");
            }
            catch (Exception)
            {
                return new Mensagem(false, "Ocorreu um erro ao excluir a colaborador!");
            }
        }

        public List<Dropdownlist> carregaColaboradores(int idEscola)
        {
            return dbContext.Usuario.
                Where(w => w.webpages_Roles.FirstOrDefault().RoleId == (int)Perfil.Diretor ||
                            w.webpages_Roles.FirstOrDefault().RoleId == (int)Perfil.Secretario ||
                            w.webpages_Roles.FirstOrDefault().RoleId == (int)Perfil.Professor).
                Except(dbContext.InstituicaoColaborador.Where(w => w.idInstituicao == idEscola).Select(s => s.Usuario)).
                OrderBy(o => o.nome).
                Select(s => new Dropdownlist() { id = s.id, nome = s.nome }).ToList();
        }
    }
}


text:
  Gambsheim est
      une commune située dans le département de Bas-Rhin en Alsace. On dénombrait 4 312 habitants en 2008.

À coté de Gambsheim sont situées les villes de
Offendorf à 3 km, 2 026 habitants,
Kilstett située à 2 km, 2 270 habitants,
Weyersheim localisée à 6 km, 3 098 habitants,
Bietlenheim localisée à 8 km, 267 habitants,
Gries à 8 km, 2 754 habitants,
Herrlisheim située à 4 km, 4 509 habitants,
 entre autres. De plus, Gambsheim est située à seulement 15 km de Strasbourg.

La commune propose de nombreux  aménagements, elle dispose, entre autres, de un terrain de tennis, un centre d'équitation, deux terrains de sport et un équipement de roller/skate.

Le nombre d'habitations, à Gambsheim, était réparti en 2011 en 613 appartements et 1 394 maisons soit
 un marché relativement équilibré.

À Gambsheim, le prix moyen à la vente d'un appartement se situe à 2 589 € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 2 284 € du m². À la location la valorisation moyenne se situe à 7,14 € du m² mensuel.

À Gambsheim le salaire moyen mensuel par individu se situe à environ 2 096 €  net. Ceci est au niveau de la moyenne du pays.


text:
package com.inepex.ineForm.client.form.panelwidgets;

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

import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.Widget;
import com.inepex.ineForm.shared.descriptorext.PanelWidgetRDesc;

public class TabPanelWidget extends PanelWidget {

    private final FlowPanel mainPanel = new FlowPanel();
    private final CustomTabPanel tabPanel = new CustomTabPanel();
    private final List<TabPageWidget> tabs = new ArrayList<TabPageWidget>();
    boolean first = true;

    public TabPanelWidget(
        PanelWidgetRDesc descriptor,
        PanelWidget parent,
        DisplayedFormUnitChangeHandler parentHandler) {
        super(descriptor, parent, parentHandler);
        initWidget(mainPanel);
        mainPanel.add(tabPanel);
    }

    @Override
    public void addToPanel(Widget w) {
        if (w instanceof TabPageWidget) {
            tabPanel.add(w, ((TabPageWidget) w).getTitleWidget());
            tabs.add((TabPageWidget) w);
            if (first) {
                tabPanel.selectTab(0, false);
                first = false;
            }
        } else {
            mainPanel.add(w);
        }
    }

    private class CustomTabPanel extends TabPanel {

        @Override
        public void selectTab(int index) {
            selectTab(index, true);
        }

        @Override
        public void selectTab(int index, boolean userAction) {
            if (userAction) {
                if (tabPanel.getTabBar().getSelectedTab() != -1) {
                    onDisplayedFormUnitChange(
                        TabPanelWidget.this,
                        tabs.get(tabPanel.getTabBar().getSelectedTab()).getFormUnits(),
                        new ChangeResponse(tabPanel.getTabBar().getSelectedTab(), index));
                }
            } else
                super.selectTab(index);
        }
    }

    private class ChangeResponse
            extends DisplayedFormUnitChangeHandler.DisplayedFormUnitChangeResponse<Integer> {

        public ChangeResponse(Integer from, Integer to) {
            super(from, to);
        }

        @Override
        public void onSuccess() {
            tabPanel.selectTab(to, false);
            onPanelWidgetRefreshed(TabPanelWidget.this);
        }

        @Override
        public void onCancel() {}
    }
}


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

import com.facebook.presto.bytecode.DynamicClassLoader;
import com.facebook.presto.metadata.BoundVariables;
import com.facebook.presto.metadata.FunctionRegistry;
import com.facebook.presto.metadata.SqlAggregationFunction;
import com.facebook.presto.operator.aggregation.state.AccumulatorState;
import com.facebook.presto.operator.aggregation.state.AccumulatorStateSerializer;
import com.facebook.presto.operator.aggregation.state.BlockState;
import com.facebook.presto.operator.aggregation.state.BlockStateSerializer;
import com.facebook.presto.operator.aggregation.state.NullableBooleanState;
import com.facebook.presto.operator.aggregation.state.NullableDoubleState;
import com.facebook.presto.operator.aggregation.state.NullableLongState;
import com.facebook.presto.operator.aggregation.state.SliceState;
import com.facebook.presto.operator.aggregation.state.StateCompiler;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;

import java.lang.invoke.MethodHandle;
import java.util.List;

import static com.facebook.presto.metadata.Signature.typeVariable;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INDEX;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.BLOCK_INPUT_CHANNEL;
import static com.facebook.presto.operator.aggregation.AggregationMetadata.ParameterMetadata.ParameterType.STATE;
import static com.facebook.presto.operator.aggregation.AggregationUtils.generateAggregationName;
import static com.facebook.presto.util.Reflection.methodHandle;

public class ArbitraryAggregationFunction
        extends SqlAggregationFunction
{
    public static final ArbitraryAggregationFunction ARBITRARY_AGGREGATION = new ArbitraryAggregationFunction();
    private static final String NAME = "arbitrary";

    private static final MethodHandle LONG_INPUT_FUNCTION = methodHandle(ArbitraryAggregationFunction.class, "input", Type.class, NullableLongState.class, Block.class, int.class);
    private static final MethodHandle DOUBLE_INPUT_FUNCTION = methodHandle(ArbitraryAggregationFunction.class, "input", Type.class, NullableDoubleState.class, Block.class, int.class);
    private static final MethodHandle SLICE_INPUT_FUNCTION = methodHandle(ArbitraryAggregationFunction.class, "input", Type.class, SliceState.class, Block.class, int.class);
    private static final MethodHandle BOOLEAN_INPUT_FUNCTION = methodHandle(ArbitraryAggregationFunction.class, "input", Type.class, NullableBooleanState.class, Block.class, int.class);
    private static final MethodHandle BLOCK_INPUT_FUNCTION = methodHandle(ArbitraryAggregationFunction.class, "input", Type.class, BlockState.class, Block.class, int.class);

    private static final MethodHandle LONG_OUTPUT_FUNCTION = methodHandle(NullableLongState.class, "write", Type.class, NullableLongState.class, BlockBuilder.class);
    private static final MethodHandle DOUBLE_OUTPUT_FUNCTION = methodHandle(NullableDoubleState.class, "write", Type.class, NullableDoubleState.class, BlockBuilder.class);
    private static final MethodHandle SLICE_OUTPUT_FUNCTION = methodHandle(SliceState.class, "write", Type.class, SliceState.class, BlockBuilder.class);
    private static final MethodHandle BOOLEAN_OUTPUT_FUNCTION = methodHandle(NullableBooleanState.class, "write", Type.class, NullableBooleanState.class, BlockBuilder.class);
    private static final MethodHandle BLOCK_OUTPUT_FUNCTION = methodHandle(BlockState.class, "write", Type.class, BlockState.class, BlockBuilder.class);

    private static final StateCompiler compiler = new StateCompiler();

    protected ArbitraryAggregationFunction()
    {
        super(NAME, ImmutableList.of(typeVariable("T")), ImmutableList.of(), "T", ImmutableList.of("T"));
    }

    @Override
    public String getDescription()
    {
        return "return an arbitrary non-null input value";
    }

    @Override
    public InternalAggregationFunction specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionRegistry functionRegistry)
    {
        Type valueType = boundVariables.getTypeVariable("T");
        return generateAggregation(valueType);
    }

    private static InternalAggregationFunction generateAggregation(Type type)
    {
        DynamicClassLoader classLoader = new DynamicClassLoader(ArbitraryAggregationFunction.class.getClassLoader());

        List<Type> inputTypes = ImmutableList.of(type);

        MethodHandle inputFunction;
        MethodHandle outputFunction;
        Class<? extends AccumulatorState> stateInterface;
        AccumulatorStateSerializer<?> stateSerializer;

        if (type.getJavaType() == long.class) {
            stateInterface = NullableLongState.class;
            stateSerializer = compiler.generateStateSerializer(stateInterface, classLoader);
            inputFunction = LONG_INPUT_FUNCTION;
            outputFunction = LONG_OUTPUT_FUNCTION;
        }
        else if (type.getJavaType() == double.class) {
            stateInterface = NullableDoubleState.class;
            stateSerializer = compiler.generateStateSerializer(stateInterface, classLoader);
            inputFunction = DOUBLE_INPUT_FUNCTION;
            outputFunction = DOUBLE_OUTPUT_FUNCTION;
        }
        else if (type.getJavaType() == Slice.class) {
            stateInterface = SliceState.class;
            stateSerializer = compiler.generateStateSerializer(stateInterface, classLoader);
            inputFunction = SLICE_INPUT_FUNCTION;
            outputFunction = SLICE_OUTPUT_FUNCTION;
        }
        else if (type.getJavaType() == boolean.class) {
            stateInterface = NullableBooleanState.class;
            stateSerializer = compiler.generateStateSerializer(stateInterface, classLoader);
            inputFunction = BOOLEAN_INPUT_FUNCTION;
            outputFunction = BOOLEAN_OUTPUT_FUNCTION;
        }
        else {
            stateInterface = BlockState.class;
            stateSerializer = new BlockStateSerializer(type);
            inputFunction = BLOCK_INPUT_FUNCTION;
            outputFunction = BLOCK_OUTPUT_FUNCTION;
        }
        inputFunction = inputFunction.bindTo(type);

        Type intermediateType = stateSerializer.getSerializedType();
        List<ParameterMetadata> inputParameterMetadata = createInputParameterMetadata(type);
        AggregationMetadata metadata = new AggregationMetadata(
                generateAggregationName(NAME, type, inputTypes),
                inputParameterMetadata,
                inputFunction,
                inputParameterMetadata,
                inputFunction,
                null,
                outputFunction.bindTo(type),
                stateInterface,
                stateSerializer,
                compiler.generateStateFactory(stateInterface, classLoader),
                type,
                false);

        GenericAccumulatorFactoryBinder factory = new AccumulatorCompiler().generateAccumulatorFactoryBinder(metadata, classLoader);
        return new InternalAggregationFunction(NAME, inputTypes, intermediateType, type, true, false, factory);
    }

    private static List<ParameterMetadata> createInputParameterMetadata(Type value)
    {
        return ImmutableList.of(new ParameterMetadata(STATE), new ParameterMetadata(BLOCK_INPUT_CHANNEL, value), new ParameterMetadata(BLOCK_INDEX));
    }

    public static void input(Type type, NullableDoubleState state, Block block, int position)
    {
        if (!state.isNull()) {
            return;
        }
        state.setNull(false);
        state.setDouble(type.getDouble(block, position));
    }

    public static void input(Type type, NullableLongState state, Block block, int position)
    {
        if (!state.isNull()) {
            return;
        }
        state.setNull(false);
        state.setLong(type.getLong(block, position));
    }

    public static void input(Type type, SliceState state, Block block, int position)
    {
        if (state.getSlice() != null) {
            return;
        }
        state.setSlice(type.getSlice(block, position));
    }

    public static void input(Type type, NullableBooleanState state, Block block, int position)
    {
        if (!state.isNull()) {
            return;
        }
        state.setNull(false);
        state.setBoolean(type.getBoolean(block, position));
    }

    public static void input(Type type, BlockState state, Block block, int position)
    {
        if (state.getBlock() != null) {
            return;
        }
        state.setBlock((Block) type.getObject(block, position));
    }
}


text:
import logging
import numpy as np

logger = logging.getLogger(__name__)

FLANN_ALGS = ['kdtree', 'kmeans', 'composite', 'lsh', 'autotuned']
CV_ALGS = ['kdtree', 'kmeans', 'composite', 'lsh', 'autotuned']
SKLEARN_ALGS = ['kd_tree', 'ball_tree', 'brute', 'auto']

def train_matcher(data, algorithm='kdtree'):
#    if algorithm in FLANN_ALGS:
#        matcher = fit_flann(data, algorithm)
#    el
    if algorithm in CV_ALGS:
        matcher = fit_cv2(data, algorithm)
    elif algorithm in SKLEARN_ALGS:
        matcher = fit_sklearn(data, algorithm)
    elif algorithm == 'lshf':
        matcher = fit_lshf(data)
    elif algorithm == 'annoy':
        matcher = fit_annoy(data)
    if not matcher:
        raise ValueError('Invalid matching algorithm: {}'.format(algorithm))
    return matcher

def find_neighbors(matcher, data, algorithm='lshf', k=2):
    logger.info('Finding (approximate) nearest neighbors...')
    if algorithm in FLANN_ALGS:
        matches = matcher.nn_index(np.float32(data), k=k)
        distances, indices = zip(*(((n1.distance, n2.distance), (n1.trainIdx, n2.trainIdx)) for n1, n2 in matches))
    elif algorithm in CV_ALGS:
        matches = matcher.knnMatch(np.float32(data), k=k)
        distances, indices = zip(*(((n1.distance, n2.distance), (n1.trainIdx, n2.trainIdx)) for n1, n2 in matches))
    elif algorithm in SKLEARN_ALGS:
        distances, indices = matcher.kneighbors(data, n_neighbors=k)
    elif algorithm == 'lshf':
        distances, indices = matcher.kneighbors(data, n_neighbors=k)
    elif algorithm == 'annoy':
        indices = []
        distances = []
        for d in data:
            index, distance = matcher.get_nns_by_vector(d, k, include_distances=True)
            indices.append(index)
            distances.append(distance)
    return distances, indices

def nearest_neighbors(test, train, algorithm='lshf', k=2):
    matcher = train_matcher(train, algorithm)
    distances, indices = find_neighbors(matcher, test, algorithm, k=k)
    return distances, indices

def fit_cv2(data, algorithm):
    logger.info('Fitting cv2 FLANN...')
    from cv2 import FlannBasedMatcher
    KDTREE = 0
    index_params = {
        'algorithm': KDTREE,
        'trees': 5,
        #'target_precision': 0.9,
        #'build_weight': 0.01,
        #'memory_weight': 0,
        #'sample_fraction': 0.1,
    }
    search_params = {'checks': 5}
    flann = FlannBasedMatcher(index_params, search_params)
    flann.add(np.float32(data))
    flann.train()
    return flann

def fit_flann(data, algorithm):
    logger.info('Fitting  FLANN...')
    from pyflann import FLANN
    matcher = FLANN(
        algorithm=algorithm,
        checks=32,
        eps=0.0,
        cb_index=0.5,
        trees=1,
        leaf_max_size=4,
        branching=32,
        iterations=5,
        centers_init='random',
        target_precision=0.9,
        build_weight=0.01,
        memory_weight=0.0,
        sample_fraction=0.1,
        log_level="warning",
        random_seed=-1,
    )
    matcher.build_index(data)
    return matcher

def fit_sklearn(data, algorithm):
    logger.info('Fitting Sklearn Matcher: {}...'.format(algorithm))
    from sklearn.neighbors import NearestNeighbors
    matcher = NearestNeighbors(
        algorithm=algorithm,
        n_neighbors=2,
        radius=1.0,
        leaf_size=30,
        metric='minkowski',
        p=2,
        metric_params=None,
        n_jobs=-1,
    )
    matcher.fit(data)
    return matcher

def fit_annoy(data, n_trees=-1):
    logger.info('Fitting Annoy Matcher...')
    from annoy import AnnoyIndex
    logger.info('Building Annoy index...')
    matcher = AnnoyIndex(data.shape[1], metric='euclidean')
    for i, d in enumerate(data):
        matcher.add_item(i, d)
    logger.info('Building Annoy Matcher...')
    matcher.build(n_trees)
    return matcher

def load_annoy(path, n_features=128):
    logger.info('Loading Annoy Index {}...'.format(path))
    from annoy import AnnoyIndex
    matcher = AnnoyIndex(n_features, metric='euclidean')
    matcher.load(path)
    return matcher

def fit_lshf(data):
    logger.info('Fitting  LSHForest...')
    from sklearn.neighbors import LSHForest
    lshf = LSHForest(
        n_estimators=20,
        min_hash_match=4,
        n_candidates=200,
        n_neighbors=2,
        radius=1.0,
        radius_cutoff_ratio=0.9,
        random_state=None,
    )
    lshf.fit(data)
    return lshf


text:
paperjs
=======

Shim repository for Paperjs


text:
title: TCP üzerinde çalışan WCF servisin bağlantısını nasıl test ederiz?
author: Olcay Bayram
layout: post
permalink: /2014/11/18/tcp-uzerinde-calisan-wcf-servisin-baglantisini-nasil-test-ederiz/
categories:
  - Yazılım
tags:
  - command
  - konsol
  - prompt
  - svcutil
  - WCF
  - Web Servis
format: aside
---
**TCP üzerinde çalışan WCF servisin bağlantısını nasıl test ederiz?**

`svcutil net.tcp://localhost:9011/YanitsizBirakmayanServis/mex`

Not: svcutil komutlarını Visual Studio Tools altında "Developer Command Prompt" ile çalıştırabilirsiniz.


text:
package com.sun.org.apache.bcel.internal.util;

import com.sun.org.apache.bcel.internal.generic.*;
import com.sun.org.apache.bcel.internal.classfile.Utility;
import com.sun.org.apache.bcel.internal.Constants;
import java.io.PrintWriter;
import java.util.*;

/* ====================================================================
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Apache" and "Apache Software Foundation" and
 *    "Apache BCEL" must not be used to endorse or promote products
 *    derived from this software without prior written permission. For
 *    written permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    "Apache BCEL", nor may "Apache" appear in their name, without
 *    prior written permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/**
 * Factory creates il.append() statements, and sets instruction targets.
 * A helper class for BCELifier.
 *
 * @see BCELifier
 * @author  M. Dahm
 */
class BCELFactory extends EmptyVisitor {
  private MethodGen       _mg;
  private PrintWriter     _out;
  private ConstantPoolGen _cp;

  BCELFactory(MethodGen mg, PrintWriter out) {
    _mg  = mg;
    _cp  = mg.getConstantPool();
    _out = out;
  }

  private HashMap branch_map = new HashMap(); // Map<Instruction, InstructionHandle>

  public void start() {
    if(!_mg.isAbstract() && !_mg.isNative()) {
      for(InstructionHandle ih = _mg.getInstructionList().getStart();
          ih != null; ih = ih.getNext()) {
        Instruction i = ih.getInstruction();

        if(i instanceof BranchInstruction) {
          branch_map.put(i, ih); // memorize container
        }

        if(ih.hasTargeters()) {
          if(i instanceof BranchInstruction) {
            _out.println("    InstructionHandle ih_" + ih.getPosition() + ";");
          } else {
            _out.print("    InstructionHandle ih_" + ih.getPosition() + " = ");
          }
        } else {
          _out.print("    ");
        }

        if(!visitInstruction(i))
          i.accept(this);
      }

      updateBranchTargets();
      updateExceptionHandlers();
    }
  }

  private boolean visitInstruction(Instruction i) {
    short opcode = i.getOpcode();

    if((InstructionConstants.INSTRUCTIONS[opcode] != null) &&
       !(i instanceof ConstantPushInstruction) &&
       !(i instanceof ReturnInstruction)) { // Handled below
      _out.println("il.append(InstructionConstants." +
                   i.getName().toUpperCase() + ");");
      return true;
    }

    return false;
  }

  public void visitLocalVariableInstruction(LocalVariableInstruction i) {
    short  opcode = i.getOpcode();
    Type   type   = i.getType(_cp);

    if(opcode == Constants.IINC) {
      _out.println("il.append(new IINC(" + i.getIndex() + ", " +
                   ((IINC)i).getIncrement() + "));");
    } else {
      String kind   = (opcode < Constants.ISTORE)? "Load" : "Store";
      _out.println("il.append(_factory.create" + kind + "(" +
                   BCELifier.printType(type) + ", " +
                   i.getIndex() + "));");
    }
  }

  public void visitArrayInstruction(ArrayInstruction i) {
    short  opcode = i.getOpcode();
    Type   type   = i.getType(_cp);
    String kind   = (opcode < Constants.IASTORE)? "Load" : "Store";

    _out.println("il.append(_factory.createArray" + kind + "(" +
                 BCELifier.printType(type) + "));");
  }

  public void visitFieldInstruction(FieldInstruction i) {
    short  opcode = i.getOpcode();

    String class_name = i.getClassName(_cp);
    String field_name = i.getFieldName(_cp);
    Type   type       = i.getFieldType(_cp);

    _out.println("il.append(_factory.createFieldAccess(\"" +
                 class_name + "\", \"" + field_name + "\", " +
                 BCELifier.printType(type) + ", " +
                 "Constants." + Constants.OPCODE_NAMES[opcode].toUpperCase() +
                 "));");
  }

  public void visitInvokeInstruction(InvokeInstruction i) {
    short  opcode      = i.getOpcode();
    String class_name  = i.getClassName(_cp);
    String method_name = i.getMethodName(_cp);
    Type   type        = i.getReturnType(_cp);
    Type[] arg_types   = i.getArgumentTypes(_cp);

    _out.println("il.append(_factory.createInvoke(\"" +
                 class_name + "\", \"" + method_name + "\", " +
                 BCELifier.printType(type) + ", " +
                 BCELifier.printArgumentTypes(arg_types) + ", " +
                 "Constants." + Constants.OPCODE_NAMES[opcode].toUpperCase() +
                 "));");
  }

  public void visitAllocationInstruction(AllocationInstruction i) {
    Type type;

    if(i instanceof CPInstruction) {
      type = ((CPInstruction)i).getType(_cp);
    } else {
      type = ((NEWARRAY)i).getType();
    }

    short opcode = ((Instruction)i).getOpcode();
    int   dim    = 1;

    switch(opcode) {
    case Constants.NEW:
      _out.println("il.append(_factory.createNew(\"" +
                   ((ObjectType)type).getClassName() + "\"));");
      break;

    case Constants.MULTIANEWARRAY:
      dim = ((MULTIANEWARRAY)i).getDimensions();

    case Constants.ANEWARRAY:
    case Constants.NEWARRAY:
      _out.println("il.append(_factory.createNewArray(" +
                   BCELifier.printType(type) + ", (short) " + dim + "));");
      break;

    default:
      throw new RuntimeException("Oops: " + opcode);
    }
  }

  private void createConstant(Object value) {
    String embed = value.toString();

    if(value instanceof String)
      embed = '"' + Utility.convertString(value.toString()) + '"';
    else if(value instanceof Character)
      embed = "(char)0x" + Integer.toHexString(((Character)value).charValue());

    _out.println("il.append(new PUSH(_cp, " + embed + "));");
  }

  public void visitLDC(LDC i) {
    createConstant(i.getValue(_cp));
  }

  public void visitLDC2_W(LDC2_W i) {
    createConstant(i.getValue(_cp));
  }

  public void visitConstantPushInstruction(ConstantPushInstruction i) {
    createConstant(i.getValue());
  }

  public void visitINSTANCEOF(INSTANCEOF i) {
    Type type = i.getType(_cp);

    _out.println("il.append(new INSTANCEOF(_cp.addClass(" +
                 BCELifier.printType(type) + ")));");
  }

  public void visitCHECKCAST(CHECKCAST i) {
    Type type = i.getType(_cp);

    _out.println("il.append(_factory.createCheckCast(" +
                 BCELifier.printType(type) + "));");
  }

  public void visitReturnInstruction(ReturnInstruction i) {
    Type type = i.getType(_cp);

    _out.println("il.append(_factory.createReturn(" +
                 BCELifier.printType(type) + "));");
  }

  // Memorize BranchInstructions that need an update
  private ArrayList branches = new ArrayList();

  public void visitBranchInstruction(BranchInstruction bi) {
    BranchHandle bh   = (BranchHandle)branch_map.get(bi);
    int          pos  = bh.getPosition();
    String       name = bi.getName() + "_" + pos;

    if(bi instanceof Select) {
      Select s = (Select)bi;
      branches.add(bi);

      StringBuffer args   = new StringBuffer("new int[] { ");
      int[]        matchs = s.getMatchs();

      for(int i=0; i < matchs.length; i++) {
        args.append(matchs[i]);

        if(i < matchs.length - 1)
          args.append(", ");
      }

      args.append(" }");

      _out.print("    Select " + name + " = new " +
                 bi.getName().toUpperCase() + "(" + args +
                 ", new InstructionHandle[] { ");

      for(int i=0; i < matchs.length; i++) {
        _out.print("null");

        if(i < matchs.length - 1)
          _out.print(", ");
      }

      _out.println(");");
    } else {
      int    t_pos  = bh.getTarget().getPosition();
      String target;

      if(pos > t_pos) {
        target = "ih_" + t_pos;
      } else {
        branches.add(bi);
        target = "null";
      }

      _out.println("    BranchInstruction " + name +
                   " = _factory.createBranchInstruction(" +
                   "Constants." + bi.getName().toUpperCase() + ", " +
                   target + ");");
    }

    if(bh.hasTargeters())
      _out.println("    ih_" + pos + " = il.append(" + name + ");");
    else
      _out.println("    il.append(" + name + ");");
  }

  public void visitRET(RET i) {
    _out.println("il.append(new RET(" + i.getIndex() + ")));");
  }

  private void updateBranchTargets() {
    for(Iterator i = branches.iterator(); i.hasNext(); ) {
      BranchInstruction bi    = (BranchInstruction)i.next();
      BranchHandle      bh    = (BranchHandle)branch_map.get(bi);
      int               pos   = bh.getPosition();
      String            name  = bi.getName() + "_" + pos;
      int               t_pos = bh.getTarget().getPosition();

      _out.println("    " + name + ".setTarget(ih_" + t_pos + ");");

      if(bi instanceof Select) {
        InstructionHandle[] ihs = ((Select)bi).getTargets();

        for(int j = 0; j < ihs.length; j++) {
          t_pos = ihs[j].getPosition();

          _out.println("    " + name + ".setTarget(" + j +
                       ", ih_" + t_pos + ");");
        }
      }
    }
  }

  private void updateExceptionHandlers() {
    CodeExceptionGen[] handlers = _mg.getExceptionHandlers();

    for(int i=0; i < handlers.length; i++) {
      CodeExceptionGen h    = handlers[i];
      String           type = (h.getCatchType() == null)?
        "null" : BCELifier.printType(h.getCatchType());

      _out.println("    method.addExceptionHandler(" +
                   "ih_" + h.getStartPC().getPosition() + ", " +
                   "ih_" + h.getEndPC().getPosition() + ", " +
                   "ih_" + h.getHandlerPC().getPosition() + ", " +
                   type + ");");
    }
  }
}


text:
package me.robinxu.mvnbook.account.service;

public class AccountServiceException
    extends Exception
{
    private static final long serialVersionUID = 949282286716874926L;

    public AccountServiceException( String message )
    {
        super( message );
    }

    public AccountServiceException( String message, Throwable throwable )
    {
        super( message, throwable );
    }
}


text:
'use strict';
module.exports = {
    FbPageApp: require('./containers/app'),
    theme: require('./themes/default')
};


text:
struct XnUSBDevice;

namespace xn
{

class ServerUSBLinuxOutDataEndpoint : virtual public IOutputConnection
{
public:
	ServerUSBLinuxOutDataEndpoint();
	virtual ~ServerUSBLinuxOutDataEndpoint();
	virtual XnStatus Init(XnUSBDevice* pUSBDevice, XnUInt16 nEndpointID, XnUInt16 nMaxPacketSize);
	virtual void Shutdown();
	virtual XnStatus Connect();
	virtual void Disconnect();
	virtual XnBool IsConnected() const;
	virtual XnUInt16 GetMaxPacketSize() const;
	virtual XnStatus Send(const void* pData, XnUInt32 nSize);
	XnStatus Reset();

private:
	XnUSBDevice* m_pUSBDevice;
	XnUInt8 m_nEndpointID;
	XnUInt16 m_nMaxPacketSize;
};

}

#endif // __XNSERVERUSBLINUXOUTDATAENDPOINT_H__


text:
package org.projectfloodlight.openflow.protocol.ver15;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.stat.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.oxs.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Set;
import io.netty.buffer.ByteBuf;
import com.google.common.hash.PrimitiveSink;
import com.google.common.hash.Funnel;

class OFBsnTlvLoopbackModeVer15 implements OFBsnTlvLoopbackMode {
    private static final Logger logger = LoggerFactory.getLogger(OFBsnTlvLoopbackModeVer15.class);
    // version: 1.5
    final static byte WIRE_VERSION = 6;
    final static int LENGTH = 5;

    // OF message fields
    private final OFBsnLoopbackMode value;
//

    // package private constructor - used by readers, builders, and factory
    OFBsnTlvLoopbackModeVer15(OFBsnLoopbackMode value) {
        if(value == null) {
            throw new NullPointerException("OFBsnTlvLoopbackModeVer15: property value cannot be null");
        }
        this.value = value;
    }

    // Accessors for OF message fields
    @Override
    public int getType() {
        return 0x92;
    }

    @Override
    public OFBsnLoopbackMode getValue() {
        return value;
    }

    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_15;
    }

    public OFBsnTlvLoopbackMode.Builder createBuilder() {
        return new BuilderWithParent(this);
    }

    static class BuilderWithParent implements OFBsnTlvLoopbackMode.Builder {
        final OFBsnTlvLoopbackModeVer15 parentMessage;

        // OF message fields
        private boolean valueSet;
        private OFBsnLoopbackMode value;

        BuilderWithParent(OFBsnTlvLoopbackModeVer15 parentMessage) {
            this.parentMessage = parentMessage;
        }

    @Override
    public int getType() {
        return 0x92;
    }

    @Override
    public OFBsnLoopbackMode getValue() {
        return value;
    }

    @Override
    public OFBsnTlvLoopbackMode.Builder setValue(OFBsnLoopbackMode value) {
        this.value = value;
        this.valueSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_15;
    }

        @Override
        public OFBsnTlvLoopbackMode build() {
                OFBsnLoopbackMode value = this.valueSet ? this.value : parentMessage.value;
                if(value == null)
                    throw new NullPointerException("Property value must not be null");

                //
                return new OFBsnTlvLoopbackModeVer15(
                    value
                );
        }

    }

    static class Builder implements OFBsnTlvLoopbackMode.Builder {
        // OF message fields
        private boolean valueSet;
        private OFBsnLoopbackMode value;

    @Override
    public int getType() {
        return 0x92;
    }

    @Override
    public OFBsnLoopbackMode getValue() {
        return value;
    }

    @Override
    public OFBsnTlvLoopbackMode.Builder setValue(OFBsnLoopbackMode value) {
        this.value = value;
        this.valueSet = true;
        return this;
    }
    @Override
    public OFVersion getVersion() {
        return OFVersion.OF_15;
    }

//
        @Override
        public OFBsnTlvLoopbackMode build() {
            if(!this.valueSet)
                throw new IllegalStateException("Property value doesn't have default value -- must be set");
            if(value == null)
                throw new NullPointerException("Property value must not be null");

            return new OFBsnTlvLoopbackModeVer15(
                    value
                );
        }

    }

    final static Reader READER = new Reader();
    static class Reader implements OFMessageReader<OFBsnTlvLoopbackMode> {
        @Override
        public OFBsnTlvLoopbackMode readFrom(ByteBuf bb) throws OFParseError {
            int start = bb.readerIndex();
            // fixed value property type == 0x92
            short type = bb.readShort();
            if(type != (short) 0x92)
                throw new OFParseError("Wrong type: Expected=0x92(0x92), got="+type);
            int length = U16.f(bb.readShort());
            if(length != 5)
                throw new OFParseError("Wrong length: Expected=5(5), got="+length);
            if(bb.readableBytes() + (bb.readerIndex() - start) < length) {
                // Buffer does not have all data yet
                bb.readerIndex(start);
                return null;
            }
            if(logger.isTraceEnabled())
                logger.trace("readFrom - length={}", length);
            OFBsnLoopbackMode value = OFBsnLoopbackModeSerializerVer15.readFrom(bb);

            OFBsnTlvLoopbackModeVer15 bsnTlvLoopbackModeVer15 = new OFBsnTlvLoopbackModeVer15(
                    value
                    );
            if(logger.isTraceEnabled())
                logger.trace("readFrom - read={}", bsnTlvLoopbackModeVer15);
            return bsnTlvLoopbackModeVer15;
        }
    }

    public void putTo(PrimitiveSink sink) {
        FUNNEL.funnel(this, sink);
    }

    final static OFBsnTlvLoopbackModeVer15Funnel FUNNEL = new OFBsnTlvLoopbackModeVer15Funnel();
    static class OFBsnTlvLoopbackModeVer15Funnel implements Funnel<OFBsnTlvLoopbackModeVer15> {
        private static final long serialVersionUID = 1L;
        @Override
        public void funnel(OFBsnTlvLoopbackModeVer15 message, PrimitiveSink sink) {
            // fixed value property type = 0x92
            sink.putShort((short) 0x92);
            // fixed value property length = 5
            sink.putShort((short) 0x5);
            OFBsnLoopbackModeSerializerVer15.putTo(message.value, sink);
        }
    }

    public void writeTo(ByteBuf bb) {
        WRITER.write(bb, this);
    }

    final static Writer WRITER = new Writer();
    static class Writer implements OFMessageWriter<OFBsnTlvLoopbackModeVer15> {
        @Override
        public void write(ByteBuf bb, OFBsnTlvLoopbackModeVer15 message) {
            // fixed value property type = 0x92
            bb.writeShort((short) 0x92);
            // fixed value property length = 5
            bb.writeShort((short) 0x5);
            OFBsnLoopbackModeSerializerVer15.writeTo(bb, message.value);

        }
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("OFBsnTlvLoopbackModeVer15(");
        b.append("value=").append(value);
        b.append(")");
        return b.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        OFBsnTlvLoopbackModeVer15 other = (OFBsnTlvLoopbackModeVer15) obj;

        if (value == null) {
            if (other.value != null)
                return false;
        } else if (!value.equals(other.value))
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;

        result = prime * result + ((value == null) ? 0 : value.hashCode());
        return result;
    }

}


text:
import time
import argparse
import Logger
import datetime
import APIFunctionsV3
import Functions
import StatCache
import Database
import pytz
import traceback
import db_objects as db
from initial_setup import initial_setup

def pull(session, redis_session, interval=60, once=False):
    while True:
        # This is timezone specific because the train schedule itself operates on ET, not UTC!
        now = datetime.datetime.now(pytz.timezone('US/Eastern'))

        if 1 <= now.hour <= 5:
            Logger.log.info('Skipping sync, time is between 1 and 6AM')
        else:
            Logger.log.info('Syncing routes to database')
            routes = [x.name for x in session.query(db.Route).all()]
            try:
                APIFunctionsV3.sync_trips_and_records(routes, session)
                # APIFunctionsV3.sync_predictions(routes, session)

                red_average = Functions.movement_average_for_stamp(session, datetime.datetime.utcnow(), 1)
                StatCache.circular_store(redis_session, "movement_average", red_average)

                orange_average = Functions.movement_average_for_stamp(session, datetime.datetime.utcnow(), 2)
                StatCache.circular_store(redis_session, "orange_movement_average", orange_average)
            except Exception as e:
                Logger.log.error('ERROR: Data pull failed, retrying in {} seconds'.format(interval))
                traceback.print_exc()

            if once:
                break
        time.sleep(interval)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--once", help="sync once; don't loop", action='store_true')
    args = parser.parse_args()

    Database.wait_for_available()
    db_session = Database.connect()
    redis_session = Database.connect_redis()
    if not Database.is_setup(db_session):
        initial_setup()

    pull(db_session, redis_session, once=args.once)