text:
#ifndef PLPGSQL_H
#define PLPGSQL_H

#include "access/xact.h"
#include "commands/event_trigger.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "utils/expandedrecord.h"

/**********************************************************************
 * Definitions
 **********************************************************************/

/* define our text domain for translations */
#undef TEXTDOMAIN
#define TEXTDOMAIN PG_TEXTDOMAIN("plpgsql")

#undef _
#define _(x) dgettext(TEXTDOMAIN, x)

/*
 * Compiler's namespace item types
 */
typedef enum PLpgSQL_nsitem_type
{
	PLPGSQL_NSTYPE_LABEL,		/* block label */
	PLPGSQL_NSTYPE_VAR,			/* scalar variable */
	PLPGSQL_NSTYPE_REC			/* composite variable */
} PLpgSQL_nsitem_type;

/*
 * A PLPGSQL_NSTYPE_LABEL stack entry must be one of these types
 */
typedef enum PLpgSQL_label_type
{
	PLPGSQL_LABEL_BLOCK,		/* DECLARE/BEGIN block */
	PLPGSQL_LABEL_LOOP,			/* looping construct */
	PLPGSQL_LABEL_OTHER			/* anything else */
} PLpgSQL_label_type;

/*
 * Datum array node types
 */
typedef enum PLpgSQL_datum_type
{
	PLPGSQL_DTYPE_VAR,
	PLPGSQL_DTYPE_ROW,
	PLPGSQL_DTYPE_REC,
	PLPGSQL_DTYPE_RECFIELD,
	PLPGSQL_DTYPE_ARRAYELEM,
	PLPGSQL_DTYPE_PROMISE
} PLpgSQL_datum_type;

/*
 * DTYPE_PROMISE datums have these possible ways of computing the promise
 */
typedef enum PLpgSQL_promise_type
{
	PLPGSQL_PROMISE_NONE = 0,	/* not a promise, or promise satisfied */
	PLPGSQL_PROMISE_TG_NAME,
	PLPGSQL_PROMISE_TG_WHEN,
	PLPGSQL_PROMISE_TG_LEVEL,
	PLPGSQL_PROMISE_TG_OP,
	PLPGSQL_PROMISE_TG_RELID,
	PLPGSQL_PROMISE_TG_TABLE_NAME,
	PLPGSQL_PROMISE_TG_TABLE_SCHEMA,
	PLPGSQL_PROMISE_TG_NARGS,
	PLPGSQL_PROMISE_TG_ARGV,
	PLPGSQL_PROMISE_TG_EVENT,
	PLPGSQL_PROMISE_TG_TAG
} PLpgSQL_promise_type;

/*
 * Variants distinguished in PLpgSQL_type structs
 */
typedef enum PLpgSQL_type_type
{
	PLPGSQL_TTYPE_SCALAR,		/* scalar types and domains */
	PLPGSQL_TTYPE_REC,			/* composite types, including RECORD */
	PLPGSQL_TTYPE_PSEUDO		/* pseudotypes */
} PLpgSQL_type_type;

/*
 * Execution tree node types
 */
typedef enum PLpgSQL_stmt_type
{
	PLPGSQL_STMT_BLOCK,
	PLPGSQL_STMT_ASSIGN,
	PLPGSQL_STMT_IF,
	PLPGSQL_STMT_CASE,
	PLPGSQL_STMT_LOOP,
	PLPGSQL_STMT_WHILE,
	PLPGSQL_STMT_FORI,
	PLPGSQL_STMT_FORS,
	PLPGSQL_STMT_FORC,
	PLPGSQL_STMT_FOREACH_A,
	PLPGSQL_STMT_EXIT,
	PLPGSQL_STMT_RETURN,
	PLPGSQL_STMT_RETURN_NEXT,
	PLPGSQL_STMT_RETURN_QUERY,
	PLPGSQL_STMT_RAISE,
	PLPGSQL_STMT_ASSERT,
	PLPGSQL_STMT_EXECSQL,
	PLPGSQL_STMT_DYNEXECUTE,
	PLPGSQL_STMT_DYNFORS,
	PLPGSQL_STMT_GETDIAG,
	PLPGSQL_STMT_OPEN,
	PLPGSQL_STMT_FETCH,
	PLPGSQL_STMT_CLOSE,
	PLPGSQL_STMT_PERFORM,
	PLPGSQL_STMT_CALL,
	PLPGSQL_STMT_COMMIT,
	PLPGSQL_STMT_ROLLBACK,
	PLPGSQL_STMT_SET
} PLpgSQL_stmt_type;

/*
 * Execution node return codes
 */
enum
{
	PLPGSQL_RC_OK,
	PLPGSQL_RC_EXIT,
	PLPGSQL_RC_RETURN,
	PLPGSQL_RC_CONTINUE
};

/*
 * GET DIAGNOSTICS information items
 */
typedef enum PLpgSQL_getdiag_kind
{
	PLPGSQL_GETDIAG_ROW_COUNT,
	PLPGSQL_GETDIAG_CONTEXT,
	PLPGSQL_GETDIAG_ERROR_CONTEXT,
	PLPGSQL_GETDIAG_ERROR_DETAIL,
	PLPGSQL_GETDIAG_ERROR_HINT,
	PLPGSQL_GETDIAG_RETURNED_SQLSTATE,
	PLPGSQL_GETDIAG_COLUMN_NAME,
	PLPGSQL_GETDIAG_CONSTRAINT_NAME,
	PLPGSQL_GETDIAG_DATATYPE_NAME,
	PLPGSQL_GETDIAG_MESSAGE_TEXT,
	PLPGSQL_GETDIAG_TABLE_NAME,
	PLPGSQL_GETDIAG_SCHEMA_NAME
} PLpgSQL_getdiag_kind;

/*
 * RAISE statement options
 */
typedef enum PLpgSQL_raise_option_type
{
	PLPGSQL_RAISEOPTION_ERRCODE,
	PLPGSQL_RAISEOPTION_MESSAGE,
	PLPGSQL_RAISEOPTION_DETAIL,
	PLPGSQL_RAISEOPTION_HINT,
	PLPGSQL_RAISEOPTION_COLUMN,
	PLPGSQL_RAISEOPTION_CONSTRAINT,
	PLPGSQL_RAISEOPTION_DATATYPE,
	PLPGSQL_RAISEOPTION_TABLE,
	PLPGSQL_RAISEOPTION_SCHEMA
} PLpgSQL_raise_option_type;

/*
 * Behavioral modes for plpgsql variable resolution
 */
typedef enum PLpgSQL_resolve_option
{
	PLPGSQL_RESOLVE_ERROR,		/* throw error if ambiguous */
	PLPGSQL_RESOLVE_VARIABLE,	/* prefer plpgsql var to table column */
	PLPGSQL_RESOLVE_COLUMN		/* prefer table column to plpgsql var */
} PLpgSQL_resolve_option;

/**********************************************************************
 * Node and structure definitions
 **********************************************************************/

/*
 * Postgres data type
 */
typedef struct PLpgSQL_type
{
	char	   *typname;		/* (simple) name of the type */
	Oid			typoid;			/* OID of the data type */
	PLpgSQL_type_type ttype;	/* PLPGSQL_TTYPE_ code */
	int16		typlen;			/* stuff copied from its pg_type entry */
	bool		typbyval;
	char		typtype;
	Oid			collation;		/* from pg_type, but can be overridden */
	bool		typisarray;		/* is "true" array, or domain over one */
	int32		atttypmod;		/* typmod (taken from someplace else) */
} PLpgSQL_type;

/*
 * SQL Query to plan and execute
 */
typedef struct PLpgSQL_expr
{
	char	   *query;
	SPIPlanPtr	plan;
	bool		cachable;			/* true if plan can be cached */
	Bitmapset  *paramnos;		/* all dnos referenced by this query */
	int			rwparam;		/* dno of read/write param, or -1 if none */

	/* function containing this expr (not set until we first parse query) */
	struct PLpgSQL_function *func;

	/* namespace chain visible to this expr */
	struct PLpgSQL_nsitem *ns;

	/* fields for "simple expression" fast-path execution: */
	Expr	   *expr_simple_expr;	/* NULL means not a simple expr */
	int			expr_simple_generation; /* plancache generation we checked */
	Oid			expr_simple_type;	/* result type Oid, if simple */
	int32		expr_simple_typmod; /* result typmod, if simple */

	/*
	 * if expr is simple AND prepared in current transaction,
	 * expr_simple_state and expr_simple_in_use are valid. Test validity by
	 * seeing if expr_simple_lxid matches current LXID.  (If not,
	 * expr_simple_state probably points at garbage!)
	 */
	ExprState  *expr_simple_state;	/* eval tree for expr_simple_expr */
	bool		expr_simple_in_use; /* true if eval tree is active */
	LocalTransactionId expr_simple_lxid;
} PLpgSQL_expr;

/*
 * Generic datum array item
 *
 * PLpgSQL_datum is the common supertype for PLpgSQL_var, PLpgSQL_row,
 * PLpgSQL_rec, PLpgSQL_recfield, and PLpgSQL_arrayelem.
 */
typedef struct PLpgSQL_datum
{
	PLpgSQL_datum_type dtype;
	int			dno;
} PLpgSQL_datum;

/*
 * Scalar or composite variable
 *
 * The variants PLpgSQL_var, PLpgSQL_row, and PLpgSQL_rec share these
 * fields.
 */
typedef struct PLpgSQL_variable
{
	PLpgSQL_datum_type dtype;
	int			dno;
	char	   *refname;
	int			lineno;
	bool		isconst;
	bool		notnull;
	PLpgSQL_expr *default_val;
} PLpgSQL_variable;

/*
 * Scalar variable
 *
 * DTYPE_VAR and DTYPE_PROMISE datums both use this struct type.
 * A PROMISE datum works exactly like a VAR datum for most purposes,
 * but if it is read without having previously been assigned to, then
 * a special "promised" value is computed and assigned to the datum
 * before the read is performed.  This technique avoids the overhead of
 * computing the variable's value in cases where we expect that many
 * functions will never read it.
 */
typedef struct PLpgSQL_var
{
	PLpgSQL_datum_type dtype;
	int			dno;
	char	   *refname;
	int			lineno;
	bool		isconst;
	bool		notnull;
	PLpgSQL_expr *default_val;
	/* end of PLpgSQL_variable fields */

	PLpgSQL_type *datatype;

	/*
	 * Variables declared as CURSOR FOR <query> are mostly like ordinary
	 * scalar variables of type refcursor, but they have these additional
	 * properties:
	 */
	PLpgSQL_expr *cursor_explicit_expr;
	int			cursor_explicit_argrow;
	int			cursor_options;

	/* Fields below here can change at runtime */

	Datum		value;
	bool		isnull;
	bool		freeval;

	/*
	 * The promise field records which "promised" value to assign if the
	 * promise must be honored.  If it's a normal variable, or the promise has
	 * been fulfilled, this is PLPGSQL_PROMISE_NONE.
	 */
	PLpgSQL_promise_type promise;
} PLpgSQL_var;

/*
 * Row variable - this represents one or more variables that are listed in an
 * INTO clause, FOR-loop targetlist, cursor argument list, etc.  We also use
 * a row to represent a function's OUT parameters when there's more than one.
 *
 * Note that there's no way to name the row as such from PL/pgSQL code,
 * so many functions don't need to support these.
 *
 * That also means that there's no real name for the row variable, so we
 * conventionally set refname to "(unnamed row)".  We could leave it NULL,
 * but it's too convenient to be able to assume that refname is valid in
 * all variants of PLpgSQL_variable.
 *
 * isconst, notnull, and default_val are unsupported (and hence
 * always zero/null) for a row.  The member variables of a row should have
 * been checked to be writable at compile time, so isconst is correctly set
 * to false.  notnull and default_val aren't applicable.
 */
typedef struct PLpgSQL_row
{
	PLpgSQL_datum_type dtype;
	int			dno;
	char	   *refname;
	int			lineno;
	bool		isconst;
	bool		notnull;
	PLpgSQL_expr *default_val;
	/* end of PLpgSQL_variable fields */

	/*
	 * rowtupdesc is only set up if we might need to convert the row into a
	 * composite datum, which currently only happens for OUT parameters.
	 * Otherwise it is NULL.
	 */
	TupleDesc	rowtupdesc;

	int			nfields;
	char	  **fieldnames;
	int		   *varnos;
} PLpgSQL_row;

/*
 * Record variable (any composite type, including RECORD)
 */
typedef struct PLpgSQL_rec
{
	PLpgSQL_datum_type dtype;
	int			dno;
	char	   *refname;
	int			lineno;
	bool		isconst;
	bool		notnull;
	PLpgSQL_expr *default_val;
	/* end of PLpgSQL_variable fields */

	PLpgSQL_type *datatype;		/* can be NULL, if rectypeid is RECORDOID */
	Oid			rectypeid;		/* declared type of variable */
	/* RECFIELDs for this record are chained together for easy access */
	int			firstfield;		/* dno of first RECFIELD, or -1 if none */

	/* Fields below here can change at runtime */

	/* We always store record variables as "expanded" records */
	ExpandedRecordHeader *erh;
} PLpgSQL_rec;

/*
 * Field in record
 */
typedef struct PLpgSQL_recfield
{
	PLpgSQL_datum_type dtype;
	int			dno;
	/* end of PLpgSQL_datum fields */

	char	   *fieldname;		/* name of field */
	int			recparentno;	/* dno of parent record */
	int			nextfield;		/* dno of next child, or -1 if none */
	uint64		rectupledescid; /* record's tupledesc ID as of last lookup */
	ExpandedRecordFieldInfo finfo;	/* field's attnum and type info */
	/* if rectupledescid == INVALID_TUPLEDESC_IDENTIFIER, finfo isn't valid */
} PLpgSQL_recfield;

/*
 * Element of array variable
 */
typedef struct PLpgSQL_arrayelem
{
	PLpgSQL_datum_type dtype;
	int			dno;
	/* end of PLpgSQL_datum fields */

	PLpgSQL_expr *subscript;
	int			arrayparentno;	/* dno of parent array variable */

	/* Remaining fields are cached info about the array variable's type */
	Oid			parenttypoid;	/* type of array variable; 0 if not yet set */
	int32		parenttypmod;	/* typmod of array variable */
	Oid			arraytypoid;	/* OID of actual array type */
	int32		arraytypmod;	/* typmod of array (and its elements too) */
	int16		arraytyplen;	/* typlen of array type */
	Oid			elemtypoid;		/* OID of array element type */
	int16		elemtyplen;		/* typlen of element type */
	bool		elemtypbyval;	/* element type is pass-by-value? */
	char		elemtypalign;	/* typalign of element type */
} PLpgSQL_arrayelem;

/*
 * Item in the compilers namespace tree
 */
typedef struct PLpgSQL_nsitem
{
	PLpgSQL_nsitem_type itemtype;

	/*
	 * For labels, itemno is a value of enum PLpgSQL_label_type. For other
	 * itemtypes, itemno is the associated PLpgSQL_datum's dno.
	 */
	int			itemno;
	struct PLpgSQL_nsitem *prev;
	char		name[FLEXIBLE_ARRAY_MEMBER];	/* nul-terminated string */
} PLpgSQL_nsitem;

/*
 * Generic execution node
 */
typedef struct PLpgSQL_stmt
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;

	/*
	 * Unique statement ID in this function (starting at 1; 0 is invalid/not
	 * set).  This can be used by a profiler as the index for an array of
	 * per-statement metrics.
	 */
	unsigned int stmtid;
} PLpgSQL_stmt;

/*
 * One EXCEPTION condition name
 */
typedef struct PLpgSQL_condition
{
	int			sqlerrstate;	/* SQLSTATE code */
	char	   *condname;		/* condition name (for debugging) */
	struct PLpgSQL_condition *next;
} PLpgSQL_condition;

/*
 * EXCEPTION block
 */
typedef struct PLpgSQL_exception_block
{
	int			sqlstate_varno;
	int			sqlerrm_varno;
	List	   *exc_list;		/* List of WHEN clauses */
} PLpgSQL_exception_block;

/*
 * One EXCEPTION ... WHEN clause
 */
typedef struct PLpgSQL_exception
{
	int			lineno;
	PLpgSQL_condition *conditions;
	List	   *action;			/* List of statements */
} PLpgSQL_exception;

/*
 * Block of statements
 */
typedef struct PLpgSQL_stmt_block
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	char	   *label;
	List	   *body;			/* List of statements */
	int			n_initvars;		/* Length of initvarnos[] */
	int		   *initvarnos;		/* dnos of variables declared in this block */
	PLpgSQL_exception_block *exceptions;
} PLpgSQL_stmt_block;

/*
 * Assign statement
 */
typedef struct PLpgSQL_stmt_assign
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	int			varno;
	PLpgSQL_expr *expr;
} PLpgSQL_stmt_assign;

/*
 * PERFORM statement
 */
typedef struct PLpgSQL_stmt_perform
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *expr;
} PLpgSQL_stmt_perform;

/*
 * CALL statement
 */
typedef struct PLpgSQL_stmt_call
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *expr;
	bool		is_call;
	PLpgSQL_variable *target;
} PLpgSQL_stmt_call;

/*
 * COMMIT statement
 */
typedef struct PLpgSQL_stmt_commit
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	bool		chain;
} PLpgSQL_stmt_commit;

/*
 * ROLLBACK statement
 */
typedef struct PLpgSQL_stmt_rollback
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	bool		chain;
} PLpgSQL_stmt_rollback;

/*
 * SET statement
 */
typedef struct PLpgSQL_stmt_set
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *expr;
} PLpgSQL_stmt_set;

/*
 * GET DIAGNOSTICS item
 */
typedef struct PLpgSQL_diag_item
{
	PLpgSQL_getdiag_kind kind;	/* id for diagnostic value desired */
	int			target;			/* where to assign it */
} PLpgSQL_diag_item;

/*
 * GET DIAGNOSTICS statement
 */
typedef struct PLpgSQL_stmt_getdiag
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	bool		is_stacked;		/* STACKED or CURRENT diagnostics area? */
	List	   *diag_items;		/* List of PLpgSQL_diag_item */
} PLpgSQL_stmt_getdiag;

/*
 * IF statement
 */
typedef struct PLpgSQL_stmt_if
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *cond;			/* boolean expression for THEN */
	List	   *then_body;		/* List of statements */
	List	   *elsif_list;		/* List of PLpgSQL_if_elsif structs */
	List	   *else_body;		/* List of statements */
} PLpgSQL_stmt_if;

/*
 * one ELSIF arm of IF statement
 */
typedef struct PLpgSQL_if_elsif
{
	int			lineno;
	PLpgSQL_expr *cond;			/* boolean expression for this case */
	List	   *stmts;			/* List of statements */
} PLpgSQL_if_elsif;

/*
 * CASE statement
 */
typedef struct PLpgSQL_stmt_case
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *t_expr;		/* test expression, or NULL if none */
	int			t_varno;		/* var to store test expression value into */
	List	   *case_when_list; /* List of PLpgSQL_case_when structs */
	bool		have_else;		/* flag needed because list could be empty */
	List	   *else_stmts;		/* List of statements */
} PLpgSQL_stmt_case;

/*
 * one arm of CASE statement
 */
typedef struct PLpgSQL_case_when
{
	int			lineno;
	PLpgSQL_expr *expr;			/* boolean expression for this case */
	List	   *stmts;			/* List of statements */
} PLpgSQL_case_when;

/*
 * Unconditional LOOP statement
 */
typedef struct PLpgSQL_stmt_loop
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	char	   *label;
	List	   *body;			/* List of statements */
} PLpgSQL_stmt_loop;

/*
 * WHILE cond LOOP statement
 */
typedef struct PLpgSQL_stmt_while
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	char	   *label;
	PLpgSQL_expr *cond;
	List	   *body;			/* List of statements */
} PLpgSQL_stmt_while;

/*
 * FOR statement with integer loopvar
 */
typedef struct PLpgSQL_stmt_fori
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	char	   *label;
	PLpgSQL_var *var;
	PLpgSQL_expr *lower;
	PLpgSQL_expr *upper;
	PLpgSQL_expr *step;			/* NULL means default (ie, BY 1) */
	int			reverse;
	List	   *body;			/* List of statements */
} PLpgSQL_stmt_fori;

/*
 * PLpgSQL_stmt_forq represents a FOR statement running over a SQL query.
 * It is the common supertype of PLpgSQL_stmt_fors, PLpgSQL_stmt_forc
 * and PLpgSQL_dynfors.
 */
typedef struct PLpgSQL_stmt_forq
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	char	   *label;
	PLpgSQL_variable *var;		/* Loop variable (record or row) */
	List	   *body;			/* List of statements */
} PLpgSQL_stmt_forq;

/*
 * FOR statement running over SELECT
 */
typedef struct PLpgSQL_stmt_fors
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	char	   *label;
	PLpgSQL_variable *var;		/* Loop variable (record or row) */
	List	   *body;			/* List of statements */
	/* end of fields that must match PLpgSQL_stmt_forq */
	PLpgSQL_expr *query;
} PLpgSQL_stmt_fors;

/*
 * FOR statement running over cursor
 */
typedef struct PLpgSQL_stmt_forc
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	char	   *label;
	PLpgSQL_variable *var;		/* Loop variable (record or row) */
	List	   *body;			/* List of statements */
	/* end of fields that must match PLpgSQL_stmt_forq */
	int			curvar;
	PLpgSQL_expr *argquery;		/* cursor arguments if any */
} PLpgSQL_stmt_forc;

/*
 * FOR statement running over EXECUTE
 */
typedef struct PLpgSQL_stmt_dynfors
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	char	   *label;
	PLpgSQL_variable *var;		/* Loop variable (record or row) */
	List	   *body;			/* List of statements */
	/* end of fields that must match PLpgSQL_stmt_forq */
	PLpgSQL_expr *query;
	List	   *params;			/* USING expressions */
} PLpgSQL_stmt_dynfors;

/*
 * FOREACH item in array loop
 */
typedef struct PLpgSQL_stmt_foreach_a
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	char	   *label;
	int			varno;			/* loop target variable */
	int			slice;			/* slice dimension, or 0 */
	PLpgSQL_expr *expr;			/* array expression */
	List	   *body;			/* List of statements */
} PLpgSQL_stmt_foreach_a;

/*
 * OPEN a curvar
 */
typedef struct PLpgSQL_stmt_open
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	int			curvar;
	int			cursor_options;
	PLpgSQL_expr *argquery;
	PLpgSQL_expr *query;
	PLpgSQL_expr *dynquery;
	List	   *params;			/* USING expressions */
} PLpgSQL_stmt_open;

/*
 * FETCH or MOVE statement
 */
typedef struct PLpgSQL_stmt_fetch
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_variable *target;	/* target (record or row) */
	int			curvar;			/* cursor variable to fetch from */
	FetchDirection direction;	/* fetch direction */
	long		how_many;		/* count, if constant (expr is NULL) */
	PLpgSQL_expr *expr;			/* count, if expression */
	bool		is_move;		/* is this a fetch or move? */
	bool		returns_multiple_rows;	/* can return more than one row? */
} PLpgSQL_stmt_fetch;

/*
 * CLOSE curvar
 */
typedef struct PLpgSQL_stmt_close
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	int			curvar;
} PLpgSQL_stmt_close;

/*
 * EXIT or CONTINUE statement
 */
typedef struct PLpgSQL_stmt_exit
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	bool		is_exit;		/* Is this an exit or a continue? */
	char	   *label;			/* NULL if it's an unlabelled EXIT/CONTINUE */
	PLpgSQL_expr *cond;
} PLpgSQL_stmt_exit;

/*
 * RETURN statement
 */
typedef struct PLpgSQL_stmt_return
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *expr;
	int			retvarno;
} PLpgSQL_stmt_return;

/*
 * RETURN NEXT statement
 */
typedef struct PLpgSQL_stmt_return_next
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *expr;
	int			retvarno;
} PLpgSQL_stmt_return_next;

/*
 * RETURN QUERY statement
 */
typedef struct PLpgSQL_stmt_return_query
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *query;		/* if static query */
	PLpgSQL_expr *dynquery;		/* if dynamic query (RETURN QUERY EXECUTE) */
	List	   *params;			/* USING arguments for dynamic query */
} PLpgSQL_stmt_return_query;

/*
 * RAISE statement
 */
typedef struct PLpgSQL_stmt_raise
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	int			elog_level;
	char	   *condname;		/* condition name, SQLSTATE, or NULL */
	char	   *message;		/* old-style message format literal, or NULL */
	List	   *params;			/* list of expressions for old-style message */
	List	   *options;		/* list of PLpgSQL_raise_option */
} PLpgSQL_stmt_raise;

/*
 * RAISE statement option
 */
typedef struct PLpgSQL_raise_option
{
	PLpgSQL_raise_option_type opt_type;
	PLpgSQL_expr *expr;
} PLpgSQL_raise_option;

/*
 * ASSERT statement
 */
typedef struct PLpgSQL_stmt_assert
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *cond;
	PLpgSQL_expr *message;
} PLpgSQL_stmt_assert;

/*
 * Generic SQL statement to execute
 */
typedef struct PLpgSQL_stmt_execsql
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *sqlstmt;
	bool		mod_stmt;		/* is the stmt INSERT/UPDATE/DELETE?  Note:
								 * mod_stmt is set when we plan the query */
	bool		into;			/* INTO supplied? */
	bool		strict;			/* INTO STRICT flag */
	PLpgSQL_variable *target;	/* INTO target (record or row) */
} PLpgSQL_stmt_execsql;

/*
 * Dynamic SQL string to execute
 */
typedef struct PLpgSQL_stmt_dynexecute
{
	PLpgSQL_stmt_type cmd_type;
	int			lineno;
	unsigned int stmtid;
	PLpgSQL_expr *query;		/* string expression */
	bool		into;			/* INTO supplied? */
	bool		strict;			/* INTO STRICT flag */
	PLpgSQL_variable *target;	/* INTO target (record or row) */
	List	   *params;			/* USING expressions */
} PLpgSQL_stmt_dynexecute;

/*
 * Hash lookup key for functions
 */
typedef struct PLpgSQL_func_hashkey
{
	Oid			funcOid;

	bool		isTrigger;		/* true if called as a trigger */

	/* be careful that pad bytes in this struct get zeroed! */

	/*
	 * For a trigger function, the OID of the trigger is part of the hash key
	 * --- we want to compile the trigger function separately for each trigger
	 * it is used with, in case the rowtype or transition table names are
	 * different.  Zero if not called as a trigger.
	 */
	Oid			trigOid;

	/*
	 * We must include the input collation as part of the hash key too,
	 * because we have to generate different plans (with different Param
	 * collations) for different collation settings.
	 */
	Oid			inputCollation;

	/*
	 * We include actual argument types in the hash key to support polymorphic
	 * PLpgSQL functions.  Be careful that extra positions are zeroed!
	 */
	Oid			argtypes[FUNC_MAX_ARGS];
} PLpgSQL_func_hashkey;

/*
 * Trigger type
 */
typedef enum PLpgSQL_trigtype
{
	PLPGSQL_DML_TRIGGER,
	PLPGSQL_EVENT_TRIGGER,
	PLPGSQL_NOT_TRIGGER
} PLpgSQL_trigtype;

/*
 * Complete compiled function
 */
typedef struct PLpgSQL_function
{
	char	   *fn_signature;
	Oid			fn_oid;
	TransactionId fn_xmin;
	ItemPointerData fn_tid;
	PLpgSQL_trigtype fn_is_trigger;
	Oid			fn_input_collation;
	PLpgSQL_func_hashkey *fn_hashkey;	/* back-link to hashtable key */
	MemoryContext fn_cxt;

	Oid			fn_rettype;
	int			fn_rettyplen;
	bool		fn_retbyval;
	bool		fn_retistuple;
	bool		fn_retisdomain;
	bool		fn_retset;
	bool		fn_readonly;
	char		fn_prokind;

	int			fn_nargs;
	int			fn_argvarnos[FUNC_MAX_ARGS];
	int			out_param_varno;
	int			found_varno;
	int			new_varno;
	int			old_varno;

	PLpgSQL_resolve_option resolve_option;

	bool		print_strict_params;

	/* extra checks */
	int			extra_warnings;
	int			extra_errors;

	/* count of statements inside function */
	unsigned int nstatements;

	/* the datums representing the function's local variables */
	int			ndatums;
	PLpgSQL_datum **datums;
	Size		copiable_size;	/* space for locally instantiated datums */

	/* function body parsetree */
	PLpgSQL_stmt_block *action;

	/* these fields change when the function is used */
	struct PLpgSQL_execstate *cur_estate;
	unsigned long use_count;
} PLpgSQL_function;

/*
 * Runtime execution data
 */
typedef struct PLpgSQL_execstate
{
	PLpgSQL_function *func;		/* function being executed */

	TriggerData *trigdata;		/* if regular trigger, data about firing */
	EventTriggerData *evtrigdata;	/* if event trigger, data about firing */

	Datum		retval;
	bool		retisnull;
	Oid			rettype;		/* type of current retval */

	Oid			fn_rettype;		/* info about declared function rettype */
	bool		retistuple;
	bool		retisset;

	bool		readonly_func;
	bool		atomic;

	char	   *exitlabel;		/* the "target" label of the current EXIT or
								 * CONTINUE stmt, if any */
	ErrorData  *cur_error;		/* current exception handler's error */

	Tuplestorestate *tuple_store;	/* SRFs accumulate results here */
	TupleDesc	tuple_store_desc;	/* descriptor for tuples in tuple_store */
	MemoryContext tuple_store_cxt;
	ResourceOwner tuple_store_owner;
	ReturnSetInfo *rsi;

	int			found_varno;

	/*
	 * The datums representing the function's local variables.  Some of these
	 * are local storage in this execstate, but some just point to the shared
	 * copy belonging to the PLpgSQL_function, depending on whether or not we
	 * need any per-execution state for the datum's dtype.
	 */
	int			ndatums;
	PLpgSQL_datum **datums;
	/* context containing variable values (same as func's SPI_proc context) */
	MemoryContext datum_context;

	/*
	 * paramLI is what we use to pass local variable values to the executor.
	 * It does not have a ParamExternData array; we just dynamically
	 * instantiate parameter data as needed.  By convention, PARAM_EXTERN
	 * Params have paramid equal to the dno of the referenced local variable.
	 */
	ParamListInfo paramLI;

	/* EState to use for "simple" expression evaluation */
	EState	   *simple_eval_estate;

	/* lookup table to use for executing type casts */
	HTAB	   *cast_hash;
	MemoryContext cast_hash_context;

	/* memory context for statement-lifespan temporary values */
	MemoryContext stmt_mcontext;	/* current stmt context, or NULL if none */
	MemoryContext stmt_mcontext_parent; /* parent of current context */

	/* temporary state for results from evaluation of query or expr */
	SPITupleTable *eval_tuptable;
	uint64		eval_processed;
	ExprContext *eval_econtext; /* for executing simple expressions */

	/* status information for error context reporting */
	PLpgSQL_stmt *err_stmt;		/* current stmt */
	const char *err_text;		/* additional state info */

	void	   *plugin_info;	/* reserved for use by optional plugin */
} PLpgSQL_execstate;

/*
 * A PLpgSQL_plugin structure represents an instrumentation plugin.
 * To instrument PL/pgSQL, a plugin library must access the rendezvous
 * variable "PLpgSQL_plugin" and set it to point to a PLpgSQL_plugin struct.
 * Typically the struct could just be static data in the plugin library.
 * We expect that a plugin would do this at library load time (_PG_init()).
 * It must also be careful to set the rendezvous variable back to NULL
 * if it is unloaded (_PG_fini()).
 *
 * This structure is basically a collection of function pointers --- at
 * various interesting points in pl_exec.c, we call these functions
 * (if the pointers are non-NULL) to give the plugin a chance to watch
 * what we are doing.
 *
 * func_setup is called when we start a function, before we've initialized
 * the local variables defined by the function.
 *
 * func_beg is called when we start a function, after we've initialized
 * the local variables.
 *
 * func_end is called at the end of a function.
 *
 * stmt_beg and stmt_end are called before and after (respectively) each
 * statement.
 *
 * Also, immediately before any call to func_setup, PL/pgSQL fills in the
 * error_callback and assign_expr fields with pointers to its own
 * plpgsql_exec_error_callback and exec_assign_expr functions.  This is
 * a somewhat ad-hoc expedient to simplify life for debugger plugins.
 */
typedef struct PLpgSQL_plugin
{
	/* Function pointers set up by the plugin */
	void		(*func_setup) (PLpgSQL_execstate *estate, PLpgSQL_function *func);
	void		(*func_beg) (PLpgSQL_execstate *estate, PLpgSQL_function *func);
	void		(*func_end) (PLpgSQL_execstate *estate, PLpgSQL_function *func);
	void		(*stmt_beg) (PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt);
	void		(*stmt_end) (PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt);

	/* Function pointers set by PL/pgSQL itself */
	void		(*error_callback) (void *arg);
	void		(*assign_expr) (PLpgSQL_execstate *estate, PLpgSQL_datum *target,
								PLpgSQL_expr *expr);
} PLpgSQL_plugin;

/*
 * Struct types used during parsing
 */

typedef struct PLword
{
	char	   *ident;			/* palloc'd converted identifier */
	bool		quoted;			/* Was it double-quoted? */
} PLword;

typedef struct PLcword
{
	List	   *idents;			/* composite identifiers (list of String) */
} PLcword;

typedef struct PLwdatum
{
	PLpgSQL_datum *datum;		/* referenced variable */
	char	   *ident;			/* valid if simple name */
	bool		quoted;
	List	   *idents;			/* valid if composite name */
} PLwdatum;

/**********************************************************************
 * Global variable declarations
 **********************************************************************/

typedef enum
{
	IDENTIFIER_LOOKUP_NORMAL,	/* normal processing of var names */
	IDENTIFIER_LOOKUP_DECLARE,	/* In DECLARE --- don't look up names */
	IDENTIFIER_LOOKUP_EXPR		/* In SQL expression --- special case */
} IdentifierLookup;

extern IdentifierLookup plpgsql_IdentifierLookup;

extern int	plpgsql_variable_conflict;

extern bool plpgsql_print_strict_params;

extern bool plpgsql_check_asserts;

/* extra compile-time and run-time checks */
#define PLPGSQL_XCHECK_NONE						0
#define PLPGSQL_XCHECK_SHADOWVAR				(1 << 1)
#define PLPGSQL_XCHECK_TOOMANYROWS				(1 << 2)
#define PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT	(1 << 3)
#define PLPGSQL_XCHECK_ALL						((int) ~0)

extern int	plpgsql_extra_warnings;
extern int	plpgsql_extra_errors;

extern bool plpgsql_check_syntax;
extern bool plpgsql_DumpExecTree;

extern PLpgSQL_stmt_block *plpgsql_parse_result;

extern int	plpgsql_nDatums;
extern PLpgSQL_datum **plpgsql_Datums;

extern char *plpgsql_error_funcname;

extern PLpgSQL_function *plpgsql_curr_compile;
extern MemoryContext plpgsql_compile_tmp_cxt;

extern PLpgSQL_plugin **plpgsql_plugin_ptr;

/**********************************************************************
 * Function declarations
 **********************************************************************/

/*
 * Functions in pl_comp.c
 */
extern PLpgSQL_function *plpgsql_compile(FunctionCallInfo fcinfo,
										 bool forValidator);
extern PLpgSQL_function *plpgsql_compile_inline(char *proc_source);
extern void plpgsql_parser_setup(struct ParseState *pstate,
								 PLpgSQL_expr *expr);
extern bool plpgsql_parse_word(char *word1, const char *yytxt, bool lookup,
							   PLwdatum *wdatum, PLword *word);
extern bool plpgsql_parse_dblword(char *word1, char *word2,
								  PLwdatum *wdatum, PLcword *cword);
extern bool plpgsql_parse_tripword(char *word1, char *word2, char *word3,
								   PLwdatum *wdatum, PLcword *cword);
extern PLpgSQL_type *plpgsql_parse_wordtype(char *ident);
extern PLpgSQL_type *plpgsql_parse_cwordtype(List *idents);
extern PLpgSQL_type *plpgsql_parse_wordrowtype(char *ident);
extern PLpgSQL_type *plpgsql_parse_cwordrowtype(List *idents);
extern PLpgSQL_type *plpgsql_build_datatype(Oid typeOid, int32 typmod,
											Oid collation);
extern PLpgSQL_variable *plpgsql_build_variable(const char *refname, int lineno,
												PLpgSQL_type *dtype,
												bool add2namespace);
extern PLpgSQL_rec *plpgsql_build_record(const char *refname, int lineno,
										 PLpgSQL_type *dtype, Oid rectypeid,
										 bool add2namespace);
extern PLpgSQL_recfield *plpgsql_build_recfield(PLpgSQL_rec *rec,
												const char *fldname);
extern int	plpgsql_recognize_err_condition(const char *condname,
											bool allow_sqlstate);
extern PLpgSQL_condition *plpgsql_parse_err_condition(char *condname);
extern void plpgsql_adddatum(PLpgSQL_datum *newdatum);
extern int	plpgsql_add_initdatums(int **varnos);
extern void plpgsql_HashTableInit(void);

/*
 * Functions in pl_handler.c
 */
extern void _PG_init(void);

/*
 * Functions in pl_exec.c
 */
extern Datum plpgsql_exec_function(PLpgSQL_function *func,
								   FunctionCallInfo fcinfo,
								   EState *simple_eval_estate,
								   bool atomic);
extern HeapTuple plpgsql_exec_trigger(PLpgSQL_function *func,
									  TriggerData *trigdata);
extern void plpgsql_exec_event_trigger(PLpgSQL_function *func,
									   EventTriggerData *trigdata);
extern void plpgsql_xact_cb(XactEvent event, void *arg);
extern void plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
							   SubTransactionId parentSubid, void *arg);
extern Oid	plpgsql_exec_get_datum_type(PLpgSQL_execstate *estate,
										PLpgSQL_datum *datum);
extern void plpgsql_exec_get_datum_type_info(PLpgSQL_execstate *estate,
											 PLpgSQL_datum *datum,
											 Oid *typeId, int32 *typMod,
											 Oid *collation);

/*
 * Functions for namespace handling in pl_funcs.c
 */
extern void plpgsql_ns_init(void);
extern void plpgsql_ns_push(const char *label,
							PLpgSQL_label_type label_type);
extern void plpgsql_ns_pop(void);
extern PLpgSQL_nsitem *plpgsql_ns_top(void);
extern void plpgsql_ns_additem(PLpgSQL_nsitem_type itemtype, int itemno, const char *name);
extern PLpgSQL_nsitem *plpgsql_ns_lookup(PLpgSQL_nsitem *ns_cur, bool localmode,
										 const char *name1, const char *name2,
										 const char *name3, int *names_used);
extern PLpgSQL_nsitem *plpgsql_ns_lookup_label(PLpgSQL_nsitem *ns_cur,
											   const char *name);
extern PLpgSQL_nsitem *plpgsql_ns_find_nearest_loop(PLpgSQL_nsitem *ns_cur);

/*
 * Other functions in pl_funcs.c
 */
extern const char *plpgsql_stmt_typename(PLpgSQL_stmt *stmt);
extern const char *plpgsql_getdiag_kindname(PLpgSQL_getdiag_kind kind);
extern void plpgsql_free_function_memory(PLpgSQL_function *func);
extern void plpgsql_dumptree(PLpgSQL_function *func);

/*
 * Scanner functions in pl_scanner.c
 */
extern int	plpgsql_base_yylex(void);
extern int	plpgsql_yylex(void);
extern void plpgsql_push_back_token(int token);
extern bool plpgsql_token_is_unreserved_keyword(int token);
extern void plpgsql_append_source_text(StringInfo buf,
									   int startlocation, int endlocation);
extern int	plpgsql_peek(void);
extern void plpgsql_peek2(int *tok1_p, int *tok2_p, int *tok1_loc,
						  int *tok2_loc);
extern void plpgsql_scanner_errposition(int location);
extern void plpgsql_yyerror(const char *message) pg_attribute_noreturn();
extern int	plpgsql_location_to_lineno(int location);
extern int	plpgsql_latest_lineno(void);
extern void plpgsql_scanner_init(const char *str);
extern void plpgsql_scanner_finish(void);

/*
 * Externs in gram.y
 */
extern int	plpgsql_yyparse(void);

#endif							/* PLPGSQL_H */


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Shoreline Lake - Advanced Sailing</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png">
    <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/manifest.json">
    <meta name="msapplication-TileColor" content="#da532c">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">
    <link rel="stylesheet" href="css/main.css">

              Subscribe

            to our newsletter
            Booking

          summer camps advanced sailing & racing

Menu

                          About Shoreline

About Shoreline

                              back

                                      History

                                      Pressroom

                                      Hours & Directions

                                      Job Opportunities

                          Boathouse

Boat House

                              back

                                      Sailing

Sailing

                                          back

Introductory Sailing

Intermediate Sailing

Advanced Sailing

Racing Club

Private Group Clinics

                                      SUP & SUP Yoga

SUP & SUP Yoga

                                          back

Introductory SUP

SUP Yoga

                                      Kayaking

Kayaking

                                          back

Introductory Kayaking

Advanced Kayaking

                                      Windsurfing

Windsurfing

                                          back

Introductory Windsurfing

Intermediate Windsurfing

Advanced Windsurfing

Private Lessons

                                      Summer Camps

Summer Camps

                                          back

Camp Shoreline

Windsurfing & Sailing

Advanced Sailing

Advanced Windsurfing

Parent FAQ

Rentals

Retail Shop

Clubs and Racing

Upcoming Events

Non-profit Paddle Days

Custom Clinics

Lake Conditions

                          American Bistro

American Bistro

                              back

                                      Bistro Menus

                                      Wine & Beer List

                                      Catering

                          Catering and Events

Catering and Events

                              back

                                      Facility and Space
Rental

                                      Team Building

                                      Catering

Catering

                                          back

Breakfast

Brunch

Lunch

BBQ

Hor d'oeuvres

Dinner

                                      Kids' Birthday Parties

                                      Weddings

Special Events

Booking & Rentals

Olympic Class Laser Summer Camps

If your experienced young sailor (ages 11-14) wants to get into single class sailing, chances are he/she will get the right challenge via Shoreline's new Olympic Class Laser Sailing Camps.

Both the Level I & II camps run from 10am-1pm during the week, with 2 slots open for each – the focus being on semi-private instruction: In this case, while these smaller boats do accommodate 2 sailors, an individual slot can be assigned to 1 camper (age 14) or 2 campers (ages 11-13).

The Laser Camps are $225 per session, and registration for both of these camps is limited to advanced sailors.

Because of the prerequisites for each, please contact Andrew Krellenstein (Shoreline's US Level 3 Sailing Coach, and Head Sailing Instructor) – featured in this Daily News piece on Shoreline's sailing program – for more info and to register (at sailing@shorelinelake.com or 650.965.7474).

              		Laser Level I (Prerequisites: Windsurfing & Sailing Camp Level II)

A 3-hour per day, 2-day course that introduces the Olympic class laser, a single handed planing hull with simple controls for advanced technique. Topics covered: Sail Trim, Heel Control, Beach Landings, Basic Aerodynamics, Sail-Shape Controls, and Capsize Self-Rescue.

              		Laser Level II (Prerequisites: Laser Level I)

A 3-hour per day, 2-day course that improves technique through sail theory and comprehensive drills. Qualifies students to sail any dinghy. Topics covered: Hydrodynamics, Dry Capsizing, Advanced Aerodynamics, and US Sailing Certification.

Sailing Camp: Level III

This advanced sailing racing camp introduces one design dinghy racing, in Capri 14.2's, to kids/teens (ages 12-16) and covers all the skills needed in preparation for racing at a high school level.

A five-day camp similar in format to the Level I & II camps (but without the Windsurfing), the Level III camp runs for three hours per day, over a five-day period during the week.

Although additional weeks may be added at a later date, this camp is currently scheduled for one week in August of 2015.

With the focus on techniques used in sailboat racing, the camp covers the most common right of way rules, how the starting sequence works, and the basics of strategy vs. tactics around the course.

In addition to comprehensive drills to improve racing skills, during the last three days of the session, a little friendly competition will ensue, in the form of a mini regatta, to test what campers have learned.

Due to the strict enrollment requirements, Shoreline is not currently accepting online registrations for Sailing Level III. Instead, Shoreline will be contacting candidates directly. However, if you feel that your camper is ready to advance to Sailing Level III, please contact the sailing instructors by email (at sailing@shorelinelake.com).

Prerequisites: Successful completion of Windsurfing & Sailing Camp Level II (or its equivalent) is required. In addition, campers must be approved by Shoreline's sailing instructors to enroll in Level III, and should be comfortable swimming and treading water.

What To Bring

Students should bring comfortable clothes, a bathing suit, a jacket or fleece, a towel, lots of sun protection, a lanyard to secure their glasses around their heads, a bottle of water, and non-skid/non-marking shoes to wear while on the boats and boards (they will get WET – tennis shoes, aqua socks, or Teva sandals work great!). No flip-flops allowed.

Please Note: Also, parents, no pets, including dogs, may enter the park, even if they are inside a vehicle when dropping off and picking up campers.

              				Times
              				Ages
              				Price

              				2:00pm-5:00pm
              				12-16
              				$350

              				2015 Dates: 1 Week (Monday-Friday)

TBA

              				Programs
              				Times
              				Daily
              				Weekly

              				Extra Camp Supervision
              				8:00 - 5:30pm
              				$45
              				$170

              				Lunch Pass
              				NA
              				$9
              				$40

              		Register

redpajama_set_name: RedPajamaGithub


text:
Linus Torvalds Thanks Microsoft for a Great Black Friday Monitor Deal
================================================================================
![Linus Torvalds](http://i1-news.softpedia-static.com/images/news2/Linus-Torvalds-Thanks-Microsoft-for-a-Great-Black-Friday-Monitor-Deal-466599-2.jpg)

> The creator of the Linux kernel now has a UHD display

**Linus Torvalds is the creator of the Linux Kernel, he advocated for years against Microsoft's practices and he often talked about Windows. These are just some of the reasons why it's funny to see him thank Microsoft, even if it's probably done sarcastically.**

The rhetoric regarding the Linux vs. Windows subject has subsided a great deal in the last few years. There have been some issues with UEFI and other similar problems, but for the most part things have quieted down.

There is no one left at the Redmond campus to call Linux a cancer and no one is making fun of Windows for crashing all the time. In fact, there has been some sort of reconciliation between the two sides, which seems to benefit everyone.

It's not like Microsoft is ready to adopt the Linux kernel for their operating system, but the new management of the company talks about Linux as a friend, especially in the cloud.

They can no longer ignore it, even if they want to. The same happened with Linus Torvalds who hasn't said anything bad about Microsoft and Windows for a long time, and that is a good thing.

### Linus Torvalds saying "thanks" to Microsoft is not something you see every day ###

The creator of the Linux kernel talked about a great Black Friday deal he got from the Microsoft store, for a UHD monitor. He shared this piece of info on Google+ and some of the users also found it amusing to read that he's giving sincere thanks to Microsoft for their great deal.

"Whee. Just installed a new monitor. 3840x2160 resolution - it's the Dell 28" UHD panel - for $299 (€241) thanks to Microsoft's black Friday deal. Thanks MS! Ok, I have to admit that it's not actually a great panel: very clear color shifts off-center, 30Hz refresh etc. But still - I'm a nut for resolution, and at $299 (€241) I decided that this will carry me over until better panels start showing up at good prices," wrote Linus on [Google+][1].

In the meantime, he is also working on the latest kernel branch, 3.18, which will probably be released sometime at the end of this week. It's not clear how things will evolve after that, especially given the fact that the holidays are approaching fast, and devs might be a little sluggish when it comes to pushing patches and new features for the next 3.19 branch.

--------------------------------------------------------------------------------

via: http://news.softpedia.com/news/Linus-Torvalds-Thanks-Microsoft-for-a-Great-Black-Friday-Monitor-Deal-466599.shtml

作者:[Silviu Stahie][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创翻译,[Linux中国](http://linux.cn/) 荣誉推出

[a]:http://news.softpedia.com/editors/browse/silviu-stahie
[1]:https://plus.google.com/+LinusTorvalds/posts/4MwQKZhGkEr


text:
package storage

import (
	"database/sql"
	"fmt"
	"log"
	"strings"

	"github.com/adampresley/sanitizer"
	_ "github.com/denisenkom/go-mssqldb"
	"github.com/mailslurper/libmailslurper/model/attachment"
	"github.com/mailslurper/libmailslurper/model/mailitem"
	"github.com/mailslurper/libmailslurper/model/search"
)

/*
MSSQLStorage implements the IStorage interface
*/
type MSSQLStorage struct {
	connectionInformation *ConnectionInformation
	db                    *sql.DB
	xssService            sanitizer.XSSServiceProvider
}

/*
NewMSSQLStorage creates a new storage object that interfaces to MSSQL
*/
func NewMSSQLStorage(connectionInformation *ConnectionInformation) *MSSQLStorage {
	return &MSSQLStorage{
		connectionInformation: connectionInformation,
		xssService:            sanitizer.NewXSSService(),
	}
}

/*
Connect to the database
*/
func (storage *MSSQLStorage) Connect() error {
	connectionString := fmt.Sprintf("Server=%s;Port=%d;User Id=%s;Password=%s;Database=%s",
		storage.connectionInformation.Address,
		storage.connectionInformation.Port,
		storage.connectionInformation.UserName,
		storage.connectionInformation.Password,
		storage.connectionInformation.Database,
	)

	db, err := sql.Open("mssql", connectionString)

	storage.db = db
	return err
}

/*
Disconnect does exactly what you think it does
*/
func (storage *MSSQLStorage) Disconnect() {
	storage.db.Close()
}

func (storage *MSSQLStorage) Create() error {
	return nil
}

/*
GetAttachment retrieves an attachment for a given mail item
*/
func (storage *MSSQLStorage) GetAttachment(mailID, attachmentID string) (attachment.Attachment, error) {
	result := attachment.Attachment{}
	var err error
	var rows *sql.Rows

	var fileName string
	var contentType string
	var content string

	getAttachmentSQL := `
		SELECT
			  attachment.fileName
			, attachment.contentType
			, attachment.content
		FROM attachment
		WHERE
			id=?
			AND mailItemId=?
	`

	if rows, err = storage.db.Query(getAttachmentSQL, attachmentID, mailID); err != nil {
		return result, fmt.Errorf("Error running query to get attachment")
	}

	defer rows.Close()
	rows.Next()
	rows.Scan(&fileName, &contentType, &content)

	result.Headers = &attachment.AttachmentHeader{
		FileName:    fileName,
		ContentType: contentType,
	}

	result.Contents = content
	return result, nil
}

/*
GetMailByID retrieves a single mail item and attachment by ID
*/
func (storage *MSSQLStorage) GetMailByID(mailItemID string) (mailitem.MailItem, error) {
	result := mailitem.MailItem{}
	attachments := make([]*attachment.Attachment, 0)

	var err error
	var rows *sql.Rows

	var dateSent string
	var fromAddress string
	var toAddressList string
	var subject string
	var xmailer string
	var body string
	var boundary sql.NullString
	var attachmentID sql.NullString
	var fileName sql.NullString
	var mailContentType string
	var attachmentContentType sql.NullString

	sqlQuery := getMailAndAttachmentsQuery(" AND mailitem.id=? ")

	if rows, err = storage.db.Query(sqlQuery, mailItemID); err != nil {
		return result, fmt.Errorf("Error running query to get mail item: %s", err.Error())
	}

	defer rows.Close()

	for rows.Next() {
		err = rows.Scan(&dateSent, &fromAddress, &toAddressList, &subject, &xmailer, &body, &mailContentType, &boundary, &attachmentID, &fileName, &attachmentContentType)
		if err != nil {
			return result, fmt.Errorf("Error scanning mail item record: %s", err.Error())
		}

		/*
		 * Only capture the mail item once. Every subsequent record is an attachment
		 */
		if result.Id == "" {
			result = mailitem.MailItem{
				Id:          mailItemID,
				DateSent:    dateSent,
				FromAddress: fromAddress,
				ToAddresses: strings.Split(toAddressList, "; "),
				Subject:     storage.xssService.SanitizeString(subject),
				XMailer:     storage.xssService.SanitizeString(xmailer),
				Body:        storage.xssService.SanitizeString(body),
				ContentType: mailContentType,
			}

			if boundary.Valid {
				result.Boundary = boundary.String
			}
		}

		if attachmentID.Valid {
			newAttachment := &attachment.Attachment{
				Id:     attachmentID.String,
				MailId: mailItemID,
				Headers: &attachment.AttachmentHeader{
					FileName:    storage.xssService.SanitizeString(fileName.String),
					ContentType: attachmentContentType.String,
				},
			}

			attachments = append(attachments, newAttachment)
		}
	}

	result.Attachments = attachments
	return result, nil
}

/*
GetMailCollection retrieves a slice of mail items starting at offset and getting length number
of records. This query is MSSQL 2005 and higher compatible.
*/
func (storage *MSSQLStorage) GetMailCollection(offset, length int, mailSearch *search.MailSearch) ([]mailitem.MailItem, error) {
	result := make([]mailitem.MailItem, 0)
	attachments := make([]*attachment.Attachment, 0)

	var err error
	var rows *sql.Rows

	var currentMailItemID string
	var currentMailItem mailitem.MailItem
	var parameters []interface{}

	var mailItemID string
	var dateSent string
	var fromAddress string
	var toAddressList string
	var subject string
	var xmailer string
	var body string
	var mailContentType string
	var boundary sql.NullString
	var attachmentID sql.NullString
	var fileName sql.NullString
	var attachmentContentType sql.NullString

	/*
	 * This query is MSSQL 2005 and higher compatible
	 */
	sqlQuery := `
		WITH pagedMailItems AS (
			SELECT
				  mailitem.id
				, mailitem.dateSent
				, mailitem.fromAddress
				, mailitem.toAddressList
				, mailitem.subject
				, mailitem.xmailer
				, mailitem.body
				, mailitem.contentType
				, mailitem.boundary
				, ROW_NUMBER() OVER (ORDER BY mailitem.dateSent DESC) AS rowNumber
			FROM mailitem
			WHERE 1=1
	`

	sqlQuery, parameters = addSearchCriteria(sqlQuery, parameters, mailSearch)

	sqlQuery = sqlQuery + `
		)
		SELECT
			  pagedMailItems.id AS mailItemID
			, pagedMailItems.dateSent
			, pagedMailItems.fromAddress
			, pagedMailItems.toAddressList
			, pagedMailItems.subject
			, pagedMailItems.xmailer
			, pagedMailItems.body
			, pagedMailItems.contentType AS mailContentType
			, pagedMailItems.boundary
			, attachment.id AS attachmentID
			, attachment.fileName
			, attachment.contentType AS attachmentContentType

		FROM pagedMailItems
			LEFT JOIN attachment ON attachment.mailItemID=pagedMailItems.id

		WHERE
			pagedMailItems.rowNumber BETWEEN ? AND ?

	`

	sqlQuery = addOrderBy(sqlQuery, "pagedMailItems", mailSearch)

	parameters = append(parameters, offset)
	parameters = append(parameters, offset+length)

	if rows, err = storage.db.Query(sqlQuery, parameters...); err != nil {
		return result, fmt.Errorf("Error running query to get mail collection: %s", err.Error())
	}

	defer rows.Close()

	currentMailItemID = ""

	for rows.Next() {
		err = rows.Scan(&mailItemID, &dateSent, &fromAddress, &toAddressList, &subject, &xmailer, &body, &mailContentType, &boundary, &attachmentID, &fileName, &attachmentContentType)
		if err != nil {
			return result, fmt.Errorf("Error scanning mail item record: %s", err.Error())
		}

		if currentMailItemID != mailItemID {
			/*
			 * If we have a mail item we are working with place the attachments with it.
			 * Then reset everything in prep for the next mail item and batch of attachments
			 */
			if currentMailItemID != "" {
				currentMailItem.Attachments = attachments
				result = append(result, currentMailItem)
			}

			currentMailItem = mailitem.MailItem{
				Id:          mailItemID,
				DateSent:    dateSent,
				FromAddress: fromAddress,
				ToAddresses: strings.Split(toAddressList, "; "),
				Subject:     storage.xssService.SanitizeString(subject),
				XMailer:     storage.xssService.SanitizeString(xmailer),
				Body:        storage.xssService.SanitizeString(body),
				ContentType: mailContentType,
			}

			if boundary.Valid {
				currentMailItem.Boundary = boundary.String
			}

			currentMailItemID = mailItemID
			attachments = make([]*attachment.Attachment, 0)
		}

		if attachmentID.Valid {
			newAttachment := &attachment.Attachment{
				Id:     attachmentID.String,
				MailId: mailItemID,
				Headers: &attachment.AttachmentHeader{
					FileName:    storage.xssService.SanitizeString(fileName.String),
					ContentType: attachmentContentType.String,
				},
			}

			attachments = append(attachments, newAttachment)
		}
	}

	/*
	 * Attach our straggler
	 */
	if currentMailItemID != "" {
		currentMailItem.Attachments = attachments
		result = append(result, currentMailItem)
	}

	return result, nil
}

/*
GetMailCount returns the number of total records in the mail items table
*/
func (storage *MSSQLStorage) GetMailCount(mailSearch *search.MailSearch) (int, error) {
	var mailItemCount int
	var err error

	sqlQuery, parameters := getMailCountQuery(mailSearch)
	if err = storage.db.QueryRow(sqlQuery, parameters...).Scan(&mailItemCount); err != nil {
		return 0, fmt.Errorf("Error running query to get mail item count: %s", err.Error())
	}

	return mailItemCount, nil
}

/*
DeleteMailsAfterDate deletes all mails after a specified date
*/
func (storage *MSSQLStorage) DeleteMailsAfterDate(startDate string) error {
	sqlQuery := getDeleteMailQuery(startDate)
	parameters := []interface{}{}
	var err error

	if len(startDate) > 0 {
		parameters = append(parameters, startDate)
	}

	_, err = storage.db.Exec(sqlQuery, parameters...)
	return err
}

/*
StoreMail writes a mail item and its attachments to the storage device. This returns the new mail ID
*/
func (storage *MSSQLStorage) StoreMail(mailItem *mailitem.MailItem) (string, error) {
	var err error
	var transaction *sql.Tx
	var statement *sql.Stmt

	/*
	 * Create a transaction and insert the new mail item
	 */
	if transaction, err = storage.db.Begin(); err != nil {
		return "", fmt.Errorf("Error starting transaction in StoreMail: %s", err.Error())
	}

	/*
	 * Insert the mail item
	 */
	if statement, err = transaction.Prepare(getInsertMailQuery()); err != nil {
		return "", fmt.Errorf("Error preparing insert statement for mail item in StoreMail: %s", err.Error())
	}

	_, err = statement.Exec(
		mailItem.Id,
		mailItem.DateSent,
		mailItem.FromAddress,
		strings.Join(mailItem.ToAddresses, "; "),
		mailItem.Subject,
		mailItem.XMailer,
		mailItem.Body,
		mailItem.ContentType,
		mailItem.Boundary,
	)

	if err != nil {
		transaction.Rollback()
		return "", fmt.Errorf("Error executing insert for mail item in StoreMail: %s", err.Error())
	}

	statement.Close()

	/*
	 * Insert attachments
	 */
	if err = storeAttachments(mailItem.Id, transaction, mailItem.Attachments); err != nil {
		transaction.Rollback()
		return "", fmt.Errorf("Unable to insert attachments in StoreMail: %s", err.Error())
	}

	transaction.Commit()
	log.Printf("New mail item written to database.\n\n")

	return mailItem.Id, nil
}


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview
 * 'settings-on-startup-page' is a settings page.
 *
 * Example:
 *
 *    <neon-animated-pages>
 *      <settings-on-startup-page prefs="{{prefs}}">
 *      </settings-on-startup-page>
 *      ... other pages ...
 *    </neon-animated-pages>
 *
 * @group Chrome Settings Elements
 * @element settings-on-startup-page
 */
Polymer({
  is: 'settings-on-startup-page',

  properties: {
    /**
     * Preferences state.
     */
    prefs: {
      type: Object,
      notify: true,
    },

    /**
     * The current active route.
     */
    currentRoute: {
      type: Object,
      notify: true,
    },

    /**
     * Enum values for the 'session.restore_on_startup' preference.
     * @private {!Object<string, number>}
     */
    prefValues_: {
      readOnly: true,
      type: Object,
      value: {
        OPEN_NEW_TAB: 5,
        CONTINUE: 1,
        OPEN_SPECIFIC: 4,
      },
    },
  },

  /**
    * Determine whether to show the user defined startup pages.
    * @param {number} restoreOnStartup Enum value from prefValues_.
    * @return {boolean} Whether the open specific pages is selected.
    * @private
    */
  showStartupUrls_: function(restoreOnStartup) {
    return restoreOnStartup == this.prefValues_.OPEN_SPECIFIC;
  },
});


text:
import { startWith } from "@most/core"
import { Disposable, Scheduler, Sink, Stream } from "@most/types"
import { Pipe } from "../common"

class StateSink<A> extends Pipe<A, A> {
  constructor(private parent: ReplayLatest<A>, public sink: Sink<A>) {
    super(sink)
  }

  event(t: number, x: A): void {
    this.parent.latestvalue = x
    this.parent.hasValue = true

    this.sink.event(t, x)
  }
}

export class ReplayLatest<A> implements Stream<A> {
  latestvalue!: A
  hasValue = false
  hasInitial

  constructor(private source: Stream<A>,
              private initialState?: A,) {
    this.hasInitial = arguments.length === 2
  }

  run(sink: Sink<A>, scheduler: Scheduler): Disposable {
    const startWithReplay = this.hasValue
      ? startWith(this.latestvalue)
      : this.hasInitial
        ? startWith(this.initialState)
        : null

    const withReplayedValue = startWithReplay ? startWithReplay(this.source) : this.source

    return withReplayedValue.run(new StateSink(this, sink), scheduler)
  }

}

export function replayLatest<A>(s: Stream<A>, initialState?: A): ReplayLatest<A> {
  if (arguments.length === 1) {
    return new ReplayLatest(s)
  } else {
    return new ReplayLatest(s, initialState)
  }
}


text:
.ui-selectable-helper {
	position: absolute;
	z-index: 100;
	border: 1px dotted black;
}


text:
Troubleshooting
===============

I have a broken zone
--------------------

A zone is considered broken when it is not receiving updates anymore.
Its status can be "ERROR" if Designate detected the error condition
or it can be stuck in "PENDING" for a long time.

Review the logs from the API, Central, Producer, Worker and MiniDNS.
Identify the transaction ID of the last successful change and the first
failing change. Using the ID, you can filter logs from the Designate
components that are related to the same transaction.
Look for log messages with ERROR level before and after
the first failing update.

Failures in updating a zone are usually related to problems in Producer,
Worker, MiniDNS or the database.

Ensure the services are running and network connectivity is not impaired.

Transient network issues can be the cause of a broken zone.
Producer and Worker are stateful services and perform attempts at restoring
failing zones over time. Restarting the services will trigger new attempts.

I have a broken pool
--------------------

I deleted a zone but it's still in the database
-----------------------------------------------

Deleted zones are flagged with "status" set to "DELETED" and "task" set to
"NONE" once the deletion process terminates successfully.

What ports should be open?
--------------------------

Port numbers are configurable: review your designate.conf

The default values are:

+------------------------+------------+----------+
| Component              | Protocol   | Port     |
| (header rows optional) |            | numbers  |
+========================+============+==========+
| Agent                  | TCP        | 5358     |
+                        +------------+----------+
|                        | UDP        | 5358     |
+------------------------+------------+----------+
| API                    | TCP        | 9001     |
+------------------------+------------+----------+
| Keystone (external)    | TCP        | 35357    |
+------------------------+------------+----------+
| MiniDNS                | TCP        | 5354     |
+                        +------------+----------+
|                        | UDP        | 5354     |
+------------------------+------------+----------+
| MySQL                  | TCP        |    3306  |
+------------------------+------------+----------+
| RabbitMQ               | TCP        |    5672  |
+------------------------+------------+----------+
| Resolvers              | TCP        | 53       |
+                        +------------+----------+
|                        | UDP        | 53       |
+------------------------+------------+----------+
| ZooKeeper              | TCP        |    2181  |
+                        +------------+----------+
|                        | TCP        | 2888,3888|
+------------------------+------------+----------+

What network protocol are used?
-------------------------------

HTTP[S] by the API, RabbitMQ and the MySQL protocol by most components,
DNS (resolution and XFR), ZooKeeper, Memcached.

What needs access to the Database?
----------------------------------

Central, MiniDNS

What needs access to RabbitMQ?
------------------------------

The API, Central, Producer, Worker, MiniDNS

What needs access to ZooKeeper?
-------------------------------

Pool and Producer

What needs access to Memcached?
-------------------------------

API and Worker

How do I monitor Designate?
---------------------------

Designate can be monitored by various
`monitoring systems listed here <https://wiki.openstack.org/wiki/Operations/Monitoring>`_

What are useful metrics to monitor?
-----------------------------------

* General host monitoring, i.e. CPU load, memory usage, disk and network I/O
* MySQL performance, errors and free disk space
* Number of zones in ACTIVE, PENDING and ERROR status
* API queries per second, broken down by "read" and "write" operation on zones,
  records, etc
* Zone change propagation time i.e. how long does it takes for a record update
  to reach the resolvers
* Log messages containing having "ERROR" level
* Quotas utilization i.e. number of existing records/zones against the
  maximum allowed
* Memcached, RabbitMQ, ZooKeeper performance and errors

What are useful metrics to review first during an incident?
-----------------------------------------------------------

* Host, network and MySQL performance metrics
* Number of zones in ACTIVE, PENDING and ERROR status
* Log messages containing having "ERROR" level


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ResourcesApi.Domain
{
    public class TaskEntity
    {
        public Guid Id { get; set; }
        public Guid UserId { get; set; }
        public string Description { get; set; }
        public bool IsFinished { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebsitePanel.EnterpriseServer;
using WebsitePanel.EnterpriseServer.Base.RDS;

namespace WebsitePanel.Portal
{
    public partial class SettingsRdsPolicy : WebsitePanelControlBase, IUserSettingsEditorControl
    {
        public void BindSettings(UserSettings settings)
        {
            var timeouts = RdsServerSettings.ScreenSaverTimeOuts;
            ddTimeout.DataSource = timeouts;
            ddTimeout.DataTextField = "Value";
            ddTimeout.DataValueField = "Key";
            ddTimeout.DataBind();

            ddTimeout.SelectedValue = settings[RdsServerSettings.LOCK_SCREEN_TIMEOUT_VALUE];
            cbTimeoutAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.LOCK_SCREEN_TIMEOUT_ADMINISTRATORS]);
            cbTimeoutUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.LOCK_SCREEN_TIMEOUT_USERS]);

            cbRunCommandAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.REMOVE_RUN_COMMAND_ADMINISTRATORS]);
            cbRunCommandUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.REMOVE_RUN_COMMAND_USERS]);

            cbPowershellAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.REMOVE_POWERSHELL_COMMAND_ADMINISTRATORS]);
            cbPowershellUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.REMOVE_POWERSHELL_COMMAND_USERS]);

            cbHideCDriveAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.HIDE_C_DRIVE_ADMINISTRATORS]);
            cbHideCDriveUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.HIDE_C_DRIVE_USERS]);

            cbShutdownAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.REMOVE_SHUTDOWN_RESTART_ADMINISTRATORS]);
            cbShutdownUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.REMOVE_SHUTDOWN_RESTART_USERS]);

            cbTaskManagerAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.DISABLE_TASK_MANAGER_ADMINISTRATORS]);
            cbTaskManagerUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.DISABLE_TASK_MANAGER_USERS]);

            cbDesktopAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.CHANGE_DESKTOP_DISABLED_ADMINISTRATORS]);
            cbDesktopUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.CHANGE_DESKTOP_DISABLED_USERS]);

            cbScreenSaverAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.SCREEN_SAVER_DISABLED_ADMINISTRATORS]);
            cbScreenSaverUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.SCREEN_SAVER_DISABLED_USERS]);

            cbViewSessionAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.RDS_VIEW_WITHOUT_PERMISSION_ADMINISTRATORS]);
            cbViewSessionUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.RDS_VIEW_WITHOUT_PERMISSION_Users]);
            cbControlSessionAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.RDS_CONTROL_WITHOUT_PERMISSION_ADMINISTRATORS]);
            cbControlSessionUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.RDS_CONTROL_WITHOUT_PERMISSION_Users]);

            cbDisableCmdAdministrators.Checked = Convert.ToBoolean(settings[RdsServerSettings.DISABLE_CMD_ADMINISTRATORS]);
            cbDisableCmdUsers.Checked = Convert.ToBoolean(settings[RdsServerSettings.DISABLE_CMD_USERS]);

            ddTreshold.SelectedValue = settings[RdsServerSettings.DRIVE_SPACE_THRESHOLD_VALUE];
        }

        public void SaveSettings(UserSettings settings)
        {
            settings[RdsServerSettings.LOCK_SCREEN_TIMEOUT_VALUE] = ddTimeout.SelectedValue;
            settings[RdsServerSettings.LOCK_SCREEN_TIMEOUT_ADMINISTRATORS] = cbTimeoutAdministrators.Checked.ToString();
            settings[RdsServerSettings.LOCK_SCREEN_TIMEOUT_USERS] = cbTimeoutUsers.Checked.ToString();
            settings[RdsServerSettings.REMOVE_RUN_COMMAND_ADMINISTRATORS] = cbRunCommandAdministrators.Checked.ToString();
            settings[RdsServerSettings.REMOVE_RUN_COMMAND_USERS] = cbRunCommandUsers.Checked.ToString();
            settings[RdsServerSettings.REMOVE_POWERSHELL_COMMAND_ADMINISTRATORS] = cbPowershellAdministrators.Checked.ToString();
            settings[RdsServerSettings.REMOVE_POWERSHELL_COMMAND_USERS] = cbPowershellUsers.Checked.ToString();
            settings[RdsServerSettings.HIDE_C_DRIVE_ADMINISTRATORS] = cbHideCDriveAdministrators.Checked.ToString();
            settings[RdsServerSettings.HIDE_C_DRIVE_USERS] = cbHideCDriveUsers.Checked.ToString();
            settings[RdsServerSettings.REMOVE_SHUTDOWN_RESTART_ADMINISTRATORS] = cbShutdownAdministrators.Checked.ToString();
            settings[RdsServerSettings.REMOVE_SHUTDOWN_RESTART_USERS] = cbShutdownUsers.Checked.ToString();
            settings[RdsServerSettings.DISABLE_TASK_MANAGER_ADMINISTRATORS] = cbTaskManagerAdministrators.Checked.ToString();
            settings[RdsServerSettings.DISABLE_TASK_MANAGER_USERS] = cbTaskManagerUsers.Checked.ToString();
            settings[RdsServerSettings.CHANGE_DESKTOP_DISABLED_ADMINISTRATORS] = cbDesktopAdministrators.Checked.ToString();
            settings[RdsServerSettings.CHANGE_DESKTOP_DISABLED_USERS] = cbDesktopUsers.Checked.ToString();
            settings[RdsServerSettings.SCREEN_SAVER_DISABLED_ADMINISTRATORS] = cbScreenSaverAdministrators.Checked.ToString();
            settings[RdsServerSettings.SCREEN_SAVER_DISABLED_USERS] = cbScreenSaverUsers.Checked.ToString();
            settings[RdsServerSettings.DRIVE_SPACE_THRESHOLD_VALUE] = ddTreshold.SelectedValue;
            settings[RdsServerSettings.RDS_VIEW_WITHOUT_PERMISSION_ADMINISTRATORS] = cbViewSessionAdministrators.Checked.ToString();
            settings[RdsServerSettings.RDS_VIEW_WITHOUT_PERMISSION_Users] = cbViewSessionUsers.Checked.ToString();
            settings[RdsServerSettings.RDS_CONTROL_WITHOUT_PERMISSION_ADMINISTRATORS] = cbControlSessionAdministrators.Checked.ToString();
            settings[RdsServerSettings.RDS_CONTROL_WITHOUT_PERMISSION_Users] = cbControlSessionUsers.Checked.ToString();
            settings[RdsServerSettings.DISABLE_CMD_ADMINISTRATORS] = cbDisableCmdAdministrators.Checked.ToString();
            settings[RdsServerSettings.DISABLE_CMD_USERS] = cbDisableCmdUsers.Checked.ToString();
        }
    }
}


text:
import os
import sqlite3
import json
import urllib2
import logging

class LastfmPlugin(object):
    logger = None
    """Logging object for LastfmPlugin"""

    conn = None
    """Connection to SQLite database"""

    api_key = None
    """Last.fm API key"""

    def __init__(self, cardinal, config):
        # Initialize logger
        self.logger = logging.getLogger(__name__)

        # Connect to or create the database
        self._connect_or_create_db(cardinal)

        if config is not None and 'api_key' in config:
            self.api_key = config['api_key']

    def _connect_or_create_db(self, cardinal):
        self.conn = None
        try:
            self.conn = sqlite3.connect(os.path.join(
                cardinal.storage_path,
                'database',
                'lastfm-%s.db' % cardinal.network
            ))
        except Exception:
            self.logger.exception("Unable to access local Last.fm database")
            return

        c = self.conn.cursor()
        c.execute(
            "CREATE TABLE IF NOT EXISTS users ("
            "   nick text collate nocase,"
            "   vhost text,"
            "   username text"
            ")"
        )
        self.conn.commit()

    def set_user(self, cardinal, user, channel, msg):
        if not self.conn:
            cardinal.sendMsg(
                channel,
                "Unable to access local Last.fm database."
            )
            self.logger.error(
                "Attempt to set username failed, no database connection"
            )
            return

        message = msg.split()
        # If using natural syntax, remove Cardinal's name
        if message[0] != '.setlastfm':
            message.pop(0)

        if len(message) < 2:
            cardinal.sendMsg(channel, "Syntax: .setlastfm <username>")
            return

        nick = user.group(1)
        vhost = user.group(3)
        username = message[1]

        c = self.conn.cursor()
        c.execute(
            "SELECT username FROM users WHERE nick=? OR vhost=?",
            (nick, vhost)
        )
        result = c.fetchone()
        if result:
            c.execute(
                "UPDATE users SET username=? WHERE nick=? OR vhost=?",
                (username, nick, vhost)
            )
        else:
            c.execute(
                "INSERT INTO users (nick, vhost, username) VALUES(?, ?, ?)",
                (nick, vhost, username)
            )
        self.conn.commit()

        cardinal.sendMsg(
            channel,
            "Your Last.fm username is now set to %s." % username
        )

    set_user.commands = ['setlastfm']
    set_user.help = ["Sets the default Last.fm username for your nick.",
                     "Syntax: .setlastfm <username>"]

    def now_playing(self, cardinal, user, channel, msg):
        # Before we do anything, let's make sure we'll be able to query Last.fm
        if self.api_key is None:
            cardinal.sendMsg(
                channel,
                "Last.fm plugin is not configured. Please set API key."
            )
            self.logger.error(
                "Attempt to get now playing failed, API key not set"
            )
            return

        if not self.conn:
            cardinal.sendMsg(
                channel,
                "Unable to access local Last.fm database."
            )
            self.logger.error(
                "Attempt to get now playing failed, no database connection"
            )
            return

        # Open the cursor for the query to find a saved Last.fm username
        c = self.conn.cursor()

        message = msg.split()

        # If using natural syntax, remove Cardinal's name
        if message[0] != '.np' and message[0] != '.nowplaying':
            message.pop(0)

        # If they supplied user parameter, use that for the query instead
        if len(message) >= 2:
            nick = message[1]
            c.execute("SELECT username FROM users WHERE nick=?", (nick,))
        else:
            nick = user.group(1)
            vhost = user.group(3)
            c.execute(
                "SELECT username FROM users WHERE nick=? OR vhost=?",
                (nick, vhost)
            )
        result = c.fetchone()

        # Use the returned username, or the entered/user's nick otherwise
        if not result:
            try:
                username = message[1]
            except IndexError:
                username = user.group(1)
        else:
            username = result[0]

        try:
            uh = urllib2.urlopen(
                "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks"
                "&user=%s&api_key=%s&limit=1&format=json" %
                (username, self.api_key)
            )
            content = json.load(uh)
        except Exception:
            cardinal.sendMsg(channel, "Unable to connect to Last.fm.")
            self.logger.exception("Failed to connect to Last.fm")
            return

        if 'error' in content and content['error'] == 10:
            cardinal.sendMsg(
                channel,
                "Last.fm plugin is not configured. Please set API key."
            )
            self.logger.error(
                "Attempt to get now playing failed, API key incorrect"
            )
            return
        elif 'error' in content and content['error'] == 6:
            cardinal.sendMsg(
                channel,
                "Your Last.fm username is incorrect. No user exists by the "
                "username %s." % str(username)
            )
            return

        try:
            song = content['recenttracks']['track'][0]['name']
            artist = content['recenttracks']['track'][0]['artist']['#text']

            cardinal.sendMsg(
                channel,
                "%s is now listening to: %s by %s" %
                (str(username), str(song), str(artist))
            )
        except IndexError:
            cardinal.sendMsg(
                channel,
                "Unable to find any tracks played. "
                "(Is your Last.fm username correct?)"
            )

    now_playing.commands = ['np', 'nowplaying']
    now_playing.help = ["Get the Last.fm track currently played by a user "
                        "(defaults to username set with .setlastfm)",
                        "Syntax: .np [username]"]

    def compare(self, cardinal, user, channel, msg):
        # Before we do anything, let's make sure we'll be able to query Last.fm
        if self.api_key is None:
            cardinal.sendMsg(
                channel,
                "Last.fm plugin is not configured correctly. "
                "Please set API key."
            )
            self.logger.error(
                "Attempt to compare users failed, API key not set"
            )
            return

        if not self.conn:
            cardinal.sendMsg(
                channel,
                "Unable to access local Last.fm database."
            )
            self.logger.error(
                "Attempt to compare users failed, no database connection"
            )
            return

        # Open the cursor for the query to find a saved Last.fm username
        c = self.conn.cursor()

        # If they supplied user parameter, use that for the query instead
        message = msg.split()

        if message[0] != '.compare':
            message.pop(0)

        if len(message) < 2:
            cardinal.sendMsg(channel, "Syntax: .compare <username> [username]")

        nick = message[1]
        c.execute("SELECT username FROM users WHERE nick=?", (nick,))
        result = c.fetchone()

        if not result:
            username1 = nick
        else:
            username1 = result[0]

        if len(message) >= 3:
            nick = message[2]
            c.execute("SELECT username FROM users WHERE nick=?", (nick,))
        else:
            nick = user.group(1)
            vhost = user.group(3)
            c.execute(
                "SELECT username FROM users WHERE nick=? OR vhost=?",
                (nick, vhost)
            )
        result = c.fetchone()

        # Use the returned username, or the entered/user's nick otherwise
        if not result:
            username2 = nick
        else:
            username2 = result[0]

        try:
            uh = urllib2.urlopen(
                "http://ws.audioscrobbler.com/2.0/?method=tasteometer.compare"
                "&type1=user&type2=user&value1=%s&value2=%s&api_key=%s"
                "&format=json" % (username1, username2, self.api_key))
            content = json.load(uh)
        except Exception:
            cardinal.sendMsg(channel, "Unable to connect to Last.fm.")
            self.logger.exception("Failed to connect to Last.fm")
            return

        if 'error' in content and content['error'] == 10:
            cardinal.sendMsg(
                channel,
                "Last.fm plugin is not configured. Please set API key."
            )
            self.logger.error(
                "Attempt to compare users failed, API key incorrect"
            )
            return
        elif 'error' in content and content['error'] == 7:
            cardinal.sendMsg(
                channel,
                "One of the Last.fm usernames was invalid. Please try again."
            )
            return

        try:
            result = content['comparison']['result']

            score = int(float(result['score']) * 100)
            artists = []
            if 'artist' not in result['artists']:
                # Return early to avoid error on looping through artists
                cardinal.sendMsg(
                    channel,
                    "According to Last.fm's Tasteometer, %s and %s share none "
                    "of the same music." %
                    (str(username1), str(username2))
                )
                return

            # Account for Last.fm giving a string instead of a list if only
            # one artist is shared
            if not isinstance(result['artists']['artist'], list):
                artists.append(str(result['artists']['artist']['name']))
            else:
                # Loop through all artists to grab artist names
                for i in range(len(result['artists']['artist'])):
                    artists.append(str(result['artists']['artist'][i]['name']))

            cardinal.sendMsg(
                channel,
                "According to Last.fm's Tasteometer, %s and %s's music "
                "preferences are %d%% compatible! Some artists they have in "
                "common include: %s" %
                (str(username1), str(username2), score, ', '.join(artists))
            )
        except KeyError:
            cardinal.sendMsg(channel, "An unknown error has occurred.")
            self.logger.exception("An unknown error occurred comparing users")

    compare.commands = ['compare']
    compare.help = ["Uses Last.fm to compare the compatibility of music "
                    "between two users.",
                    "Syntax: .compare <username> [username]"]

    def close(self):
        if self.conn:
            self.conn.close()

def setup(cardinal, config):
    return LastfmPlugin(cardinal, config)