text:
#ifndef LINUX_DMAENGINE_H
#define LINUX_DMAENGINE_H

#include <linux/device.h>
#include <linux/uio.h>
#include <linux/bug.h>
#include <linux/scatterlist.h>
#include <linux/bitmap.h>
#include <linux/types.h>
#include <asm/page.h>

/**
 * typedef dma_cookie_t - an opaque DMA cookie
 *
 * if dma_cookie_t is >0 it's a DMA request cookie, <0 it's an error code
 */
typedef s32 dma_cookie_t;
#define DMA_MIN_COOKIE	1
#define DMA_MAX_COOKIE	INT_MAX

#define dma_submit_error(cookie) ((cookie) < 0 ? 1 : 0)

/**
 * enum dma_status - DMA transaction status
 * @DMA_SUCCESS: transaction completed successfully
 * @DMA_IN_PROGRESS: transaction not yet processed
 * @DMA_PAUSED: transaction is paused
 * @DMA_ERROR: transaction failed
 */
enum dma_status {
	DMA_SUCCESS,
	DMA_IN_PROGRESS,
	DMA_PAUSED,
	DMA_ERROR,
};

/**
 * enum dma_transaction_type - DMA transaction types/indexes
 *
 * Note: The DMA_ASYNC_TX capability is not to be set by drivers.  It is
 * automatically set as dma devices are registered.
 */
enum dma_transaction_type {
	DMA_MEMCPY,
	DMA_XOR,
	DMA_PQ,
	DMA_XOR_VAL,
	DMA_PQ_VAL,
	DMA_MEMSET,
	DMA_INTERRUPT,
	DMA_SG,
	DMA_PRIVATE,
	DMA_ASYNC_TX,
	DMA_SLAVE,
	DMA_CYCLIC,
	DMA_INTERLEAVE,
/* last transaction type for creation of the capabilities mask */
	DMA_TX_TYPE_END,
};

/**
 * enum dma_transfer_direction - dma transfer mode and direction indicator
 * @DMA_MEM_TO_MEM: Async/Memcpy mode
 * @DMA_MEM_TO_DEV: Slave mode & From Memory to Device
 * @DMA_DEV_TO_MEM: Slave mode & From Device to Memory
 * @DMA_DEV_TO_DEV: Slave mode & From Device to Device
 */
enum dma_transfer_direction {
	DMA_MEM_TO_MEM,
	DMA_MEM_TO_DEV,
	DMA_DEV_TO_MEM,
	DMA_DEV_TO_DEV,
	DMA_TRANS_NONE,
};

/**
 * Interleaved Transfer Request
 * ----------------------------
 * A chunk is collection of contiguous bytes to be transfered.
 * The gap(in bytes) between two chunks is called inter-chunk-gap(ICG).
 * ICGs may or maynot change between chunks.
 * A FRAME is the smallest series of contiguous {chunk,icg} pairs,
 *  that when repeated an integral number of times, specifies the transfer.
 * A transfer template is specification of a Frame, the number of times
 *  it is to be repeated and other per-transfer attributes.
 *
 * Practically, a client driver would have ready a template for each
 *  type of transfer it is going to need during its lifetime and
 *  set only 'src_start' and 'dst_start' before submitting the requests.
 *
 *
 *  |      Frame-1        |       Frame-2       | ~ |       Frame-'numf'  |
 *  |====....==.===...=...|====....==.===...=...| ~ |====....==.===...=...|
 *
 *    ==  Chunk size
 *    ... ICG
 */

/**
 * struct data_chunk - Element of scatter-gather list that makes a frame.
 * @size: Number of bytes to read from source.
 *	  size_dst := fn(op, size_src), so doesn't mean much for destination.
 * @icg: Number of bytes to jump after last src/dst address of this
 *	 chunk and before first src/dst address for next chunk.
 *	 Ignored for dst(assumed 0), if dst_inc is true and dst_sgl is false.
 *	 Ignored for src(assumed 0), if src_inc is true and src_sgl is false.
 */
struct data_chunk {
	size_t size;
	size_t icg;
};

/**
 * struct dma_interleaved_template - Template to convey DMAC the transfer pattern
 *	 and attributes.
 * @src_start: Bus address of source for the first chunk.
 * @dst_start: Bus address of destination for the first chunk.
 * @dir: Specifies the type of Source and Destination.
 * @src_inc: If the source address increments after reading from it.
 * @dst_inc: If the destination address increments after writing to it.
 * @src_sgl: If the 'icg' of sgl[] applies to Source (scattered read).
 *		Otherwise, source is read contiguously (icg ignored).
 *		Ignored if src_inc is false.
 * @dst_sgl: If the 'icg' of sgl[] applies to Destination (scattered write).
 *		Otherwise, destination is filled contiguously (icg ignored).
 *		Ignored if dst_inc is false.
 * @numf: Number of frames in this template.
 * @frame_size: Number of chunks in a frame i.e, size of sgl[].
 * @sgl: Array of {chunk,icg} pairs that make up a frame.
 */
struct dma_interleaved_template {
	dma_addr_t src_start;
	dma_addr_t dst_start;
	enum dma_transfer_direction dir;
	bool src_inc;
	bool dst_inc;
	bool src_sgl;
	bool dst_sgl;
	size_t numf;
	size_t frame_size;
	struct data_chunk sgl[0];
};

/**
 * enum dma_ctrl_flags - DMA flags to augment operation preparation,
 *  control completion, and communicate status.
 * @DMA_PREP_INTERRUPT - trigger an interrupt (callback) upon completion of
 *  this transaction
 * @DMA_CTRL_ACK - if clear, the descriptor cannot be reused until the client
 *  acknowledges receipt, i.e. has has a chance to establish any dependency
 *  chains
 * @DMA_COMPL_SKIP_SRC_UNMAP - set to disable dma-unmapping the source buffer(s)
 * @DMA_COMPL_SKIP_DEST_UNMAP - set to disable dma-unmapping the destination(s)
 * @DMA_COMPL_SRC_UNMAP_SINGLE - set to do the source dma-unmapping as single
 * 	(if not set, do the source dma-unmapping as page)
 * @DMA_COMPL_DEST_UNMAP_SINGLE - set to do the destination dma-unmapping as single
 * 	(if not set, do the destination dma-unmapping as page)
 * @DMA_PREP_PQ_DISABLE_P - prevent generation of P while generating Q
 * @DMA_PREP_PQ_DISABLE_Q - prevent generation of Q while generating P
 * @DMA_PREP_CONTINUE - indicate to a driver that it is reusing buffers as
 *  sources that were the result of a previous operation, in the case of a PQ
 *  operation it continues the calculation with new sources
 * @DMA_PREP_FENCE - tell the driver that subsequent operations depend
 *  on the result of this operation
 */
enum dma_ctrl_flags {
	DMA_PREP_INTERRUPT = (1 << 0),
	DMA_CTRL_ACK = (1 << 1),
	DMA_COMPL_SKIP_SRC_UNMAP = (1 << 2),
	DMA_COMPL_SKIP_DEST_UNMAP = (1 << 3),
	DMA_COMPL_SRC_UNMAP_SINGLE = (1 << 4),
	DMA_COMPL_DEST_UNMAP_SINGLE = (1 << 5),
	DMA_PREP_PQ_DISABLE_P = (1 << 6),
	DMA_PREP_PQ_DISABLE_Q = (1 << 7),
	DMA_PREP_CONTINUE = (1 << 8),
	DMA_PREP_FENCE = (1 << 9),
};

/**
 * enum dma_ctrl_cmd - DMA operations that can optionally be exercised
 * on a running channel.
 * @DMA_TERMINATE_ALL: terminate all ongoing transfers
 * @DMA_PAUSE: pause ongoing transfers
 * @DMA_RESUME: resume paused transfer
 * @DMA_SLAVE_CONFIG: this command is only implemented by DMA controllers
 * that need to runtime reconfigure the slave channels (as opposed to passing
 * configuration data in statically from the platform). An additional
 * argument of struct dma_slave_config must be passed in with this
 * command.
 * @FSLDMA_EXTERNAL_START: this command will put the Freescale DMA controller
 * into external start mode.
 */
enum dma_ctrl_cmd {
	DMA_TERMINATE_ALL,
	DMA_PAUSE,
	DMA_RESUME,
	DMA_SLAVE_CONFIG,
	FSLDMA_EXTERNAL_START,
};

/**
 * enum sum_check_bits - bit position of pq_check_flags
 */
enum sum_check_bits {
	SUM_CHECK_P = 0,
	SUM_CHECK_Q = 1,
};

/**
 * enum pq_check_flags - result of async_{xor,pq}_zero_sum operations
 * @SUM_CHECK_P_RESULT - 1 if xor zero sum error, 0 otherwise
 * @SUM_CHECK_Q_RESULT - 1 if reed-solomon zero sum error, 0 otherwise
 */
enum sum_check_flags {
	SUM_CHECK_P_RESULT = (1 << SUM_CHECK_P),
	SUM_CHECK_Q_RESULT = (1 << SUM_CHECK_Q),
};

/**
 * dma_cap_mask_t - capabilities bitmap modeled after cpumask_t.
 * See linux/cpumask.h
 */
typedef struct { DECLARE_BITMAP(bits, DMA_TX_TYPE_END); } dma_cap_mask_t;

/**
 * struct dma_chan_percpu - the per-CPU part of struct dma_chan
 * @memcpy_count: transaction counter
 * @bytes_transferred: byte counter
 */

struct dma_chan_percpu {
	/* stats */
	unsigned long memcpy_count;
	unsigned long bytes_transferred;
};

/**
 * struct dma_chan - devices supply DMA channels, clients use them
 * @device: ptr to the dma device who supplies this channel, always !%NULL
 * @cookie: last cookie value returned to client
 * @completed_cookie: last completed cookie for this channel
 * @chan_id: channel ID for sysfs
 * @dev: class device for sysfs
 * @device_node: used to add this to the device chan list
 * @local: per-cpu pointer to a struct dma_chan_percpu
 * @client-count: how many clients are using this channel
 * @table_count: number of appearances in the mem-to-mem allocation table
 * @private: private data for certain client-channel associations
 */
struct dma_chan {
	struct dma_device *device;
	dma_cookie_t cookie;
	dma_cookie_t completed_cookie;

	/* sysfs */
	int chan_id;
	struct dma_chan_dev *dev;

	struct list_head device_node;
	struct dma_chan_percpu __percpu *local;
	int client_count;
	int table_count;
	void *private;
};

/**
 * struct dma_chan_dev - relate sysfs device node to backing channel device
 * @chan - driver channel device
 * @device - sysfs device
 * @dev_id - parent dma_device dev_id
 * @idr_ref - reference count to gate release of dma_device dev_id
 */
struct dma_chan_dev {
	struct dma_chan *chan;
	struct device device;
	int dev_id;
	atomic_t *idr_ref;
};

/**
 * enum dma_slave_buswidth - defines bus with of the DMA slave
 * device, source or target buses
 */
enum dma_slave_buswidth {
	DMA_SLAVE_BUSWIDTH_UNDEFINED = 0,
	DMA_SLAVE_BUSWIDTH_1_BYTE = 1,
	DMA_SLAVE_BUSWIDTH_2_BYTES = 2,
	DMA_SLAVE_BUSWIDTH_4_BYTES = 4,
	DMA_SLAVE_BUSWIDTH_8_BYTES = 8,
};

/**
 * struct dma_slave_config - dma slave channel runtime config
 * @direction: whether the data shall go in or out on this slave
 * channel, right now. DMA_TO_DEVICE and DMA_FROM_DEVICE are
 * legal values, DMA_BIDIRECTIONAL is not acceptable since we
 * need to differentiate source and target addresses.
 * @src_addr: this is the physical address where DMA slave data
 * should be read (RX), if the source is memory this argument is
 * ignored.
 * @dst_addr: this is the physical address where DMA slave data
 * should be written (TX), if the source is memory this argument
 * is ignored.
 * @src_addr_width: this is the width in bytes of the source (RX)
 * register where DMA data shall be read. If the source
 * is memory this may be ignored depending on architecture.
 * Legal values: 1, 2, 4, 8.
 * @dst_addr_width: same as src_addr_width but for destination
 * target (TX) mutatis mutandis.
 * @src_maxburst: the maximum number of words (note: words, as in
 * units of the src_addr_width member, not bytes) that can be sent
 * in one burst to the device. Typically something like half the
 * FIFO depth on I/O peripherals so you don't overflow it. This
 * may or may not be applicable on memory sources.
 * @dst_maxburst: same as src_maxburst but for destination target
 * mutatis mutandis.
 * @device_fc: Flow Controller Settings. Only valid for slave channels. Fill
 * with 'true' if peripheral should be flow controller. Direction will be
 * selected at Runtime.
 *
 * This struct is passed in as configuration data to a DMA engine
 * in order to set up a certain channel for DMA transport at runtime.
 * The DMA device/engine has to provide support for an additional
 * command in the channel config interface, DMA_SLAVE_CONFIG
 * and this struct will then be passed in as an argument to the
 * DMA engine device_control() function.
 *
 * The rationale for adding configuration information to this struct
 * is as follows: if it is likely that most DMA slave controllers in
 * the world will support the configuration option, then make it
 * generic. If not: if it is fixed so that it be sent in static from
 * the platform data, then prefer to do that. Else, if it is neither
 * fixed at runtime, nor generic enough (such as bus mastership on
 * some CPU family and whatnot) then create a custom slave config
 * struct and pass that, then make this config a member of that
 * struct, if applicable.
 */
struct dma_slave_config {
	enum dma_transfer_direction direction;
	dma_addr_t src_addr;
	dma_addr_t dst_addr;
	enum dma_slave_buswidth src_addr_width;
	enum dma_slave_buswidth dst_addr_width;
	u32 src_maxburst;
	u32 dst_maxburst;
	bool device_fc;
};

static inline const char *dma_chan_name(struct dma_chan *chan)
{
	return dev_name(&chan->dev->device);
}

void dma_chan_cleanup(struct kref *kref);

/**
 * typedef dma_filter_fn - callback filter for dma_request_channel
 * @chan: channel to be reviewed
 * @filter_param: opaque parameter passed through dma_request_channel
 *
 * When this optional parameter is specified in a call to dma_request_channel a
 * suitable channel is passed to this routine for further dispositioning before
 * being returned.  Where 'suitable' indicates a non-busy channel that
 * satisfies the given capability mask.  It returns 'true' to indicate that the
 * channel is suitable.
 */
typedef bool (*dma_filter_fn)(struct dma_chan *chan, void *filter_param);

typedef void (*dma_async_tx_callback)(void *dma_async_param);
/**
 * struct dma_async_tx_descriptor - async transaction descriptor
 * ---dma generic offload fields---
 * @cookie: tracking cookie for this transaction, set to -EBUSY if
 *	this tx is sitting on a dependency list
 * @flags: flags to augment operation preparation, control completion, and
 * 	communicate status
 * @phys: physical address of the descriptor
 * @chan: target channel for this operation
 * @tx_submit: set the prepared descriptor(s) to be executed by the engine
 * @callback: routine to call after this operation is complete
 * @callback_param: general parameter to pass to the callback routine
 * ---async_tx api specific fields---
 * @next: at completion submit this descriptor
 * @parent: pointer to the next level up in the dependency chain
 * @lock: protect the parent and next pointers
 */
struct dma_async_tx_descriptor {
	dma_cookie_t cookie;
	enum dma_ctrl_flags flags; /* not a 'long' to pack with cookie */
	dma_addr_t phys;
	struct dma_chan *chan;
	dma_cookie_t (*tx_submit)(struct dma_async_tx_descriptor *tx);
	dma_async_tx_callback callback;
	void *callback_param;
#ifdef CONFIG_ASYNC_TX_ENABLE_CHANNEL_SWITCH
	struct dma_async_tx_descriptor *next;
	struct dma_async_tx_descriptor *parent;
	spinlock_t lock;
#endif
};

#ifndef CONFIG_ASYNC_TX_ENABLE_CHANNEL_SWITCH
static inline void txd_lock(struct dma_async_tx_descriptor *txd)
{
}
static inline void txd_unlock(struct dma_async_tx_descriptor *txd)
{
}
static inline void txd_chain(struct dma_async_tx_descriptor *txd, struct dma_async_tx_descriptor *next)
{
	BUG();
}
static inline void txd_clear_parent(struct dma_async_tx_descriptor *txd)
{
}
static inline void txd_clear_next(struct dma_async_tx_descriptor *txd)
{
}
static inline struct dma_async_tx_descriptor *txd_next(struct dma_async_tx_descriptor *txd)
{
	return NULL;
}
static inline struct dma_async_tx_descriptor *txd_parent(struct dma_async_tx_descriptor *txd)
{
	return NULL;
}

#else
static inline void txd_lock(struct dma_async_tx_descriptor *txd)
{
	spin_lock_bh(&txd->lock);
}
static inline void txd_unlock(struct dma_async_tx_descriptor *txd)
{
	spin_unlock_bh(&txd->lock);
}
static inline void txd_chain(struct dma_async_tx_descriptor *txd, struct dma_async_tx_descriptor *next)
{
	txd->next = next;
	next->parent = txd;
}
static inline void txd_clear_parent(struct dma_async_tx_descriptor *txd)
{
	txd->parent = NULL;
}
static inline void txd_clear_next(struct dma_async_tx_descriptor *txd)
{
	txd->next = NULL;
}
static inline struct dma_async_tx_descriptor *txd_parent(struct dma_async_tx_descriptor *txd)
{
	return txd->parent;
}
static inline struct dma_async_tx_descriptor *txd_next(struct dma_async_tx_descriptor *txd)
{
	return txd->next;
}
#endif

/**
 * struct dma_tx_state - filled in to report the status of
 * a transfer.
 * @last: last completed DMA cookie
 * @used: last issued DMA cookie (i.e. the one in progress)
 * @residue: the remaining number of bytes left to transmit
 *	on the selected transfer for states DMA_IN_PROGRESS and
 *	DMA_PAUSED if this is implemented in the driver, else 0
 */
struct dma_tx_state {
	dma_cookie_t last;
	dma_cookie_t used;
	u32 residue;
};

/**
 * struct dma_device - info on the entity supplying DMA services
 * @chancnt: how many DMA channels are supported
 * @privatecnt: how many DMA channels are requested by dma_request_channel
 * @channels: the list of struct dma_chan
 * @global_node: list_head for global dma_device_list
 * @cap_mask: one or more dma_capability flags
 * @max_xor: maximum number of xor sources, 0 if no capability
 * @max_pq: maximum number of PQ sources and PQ-continue capability
 * @copy_align: alignment shift for memcpy operations
 * @xor_align: alignment shift for xor operations
 * @pq_align: alignment shift for pq operations
 * @fill_align: alignment shift for memset operations
 * @dev_id: unique device ID
 * @dev: struct device reference for dma mapping api
 * @device_alloc_chan_resources: allocate resources and return the
 *	number of allocated descriptors
 * @device_free_chan_resources: release DMA channel's resources
 * @device_prep_dma_memcpy: prepares a memcpy operation
 * @device_prep_dma_xor: prepares a xor operation
 * @device_prep_dma_xor_val: prepares a xor validation operation
 * @device_prep_dma_pq: prepares a pq operation
 * @device_prep_dma_pq_val: prepares a pqzero_sum operation
 * @device_prep_dma_memset: prepares a memset operation
 * @device_prep_dma_interrupt: prepares an end of chain interrupt operation
 * @device_prep_slave_sg: prepares a slave dma operation
 * @device_prep_dma_cyclic: prepare a cyclic dma operation suitable for audio.
 *	The function takes a buffer of size buf_len. The callback function will
 *	be called after period_len bytes have been transferred.
 * @device_prep_interleaved_dma: Transfer expression in a generic way.
 * @device_control: manipulate all pending operations on a channel, returns
 *	zero or error code
 * @device_tx_status: poll for transaction completion, the optional
 *	txstate parameter can be supplied with a pointer to get a
 *	struct with auxiliary transfer status information, otherwise the call
 *	will just return a simple status code
 * @device_issue_pending: push pending transactions to hardware
 */
struct dma_device {

	unsigned int chancnt;
	unsigned int privatecnt;
	struct list_head channels;
	struct list_head global_node;
	dma_cap_mask_t  cap_mask;
	unsigned short max_xor;
	unsigned short max_pq;
	u8 copy_align;
	u8 xor_align;
	u8 pq_align;
	u8 fill_align;
	#define DMA_HAS_PQ_CONTINUE (1 << 15)

	int dev_id;
	struct device *dev;

	int (*device_alloc_chan_resources)(struct dma_chan *chan);
	void (*device_free_chan_resources)(struct dma_chan *chan);

	struct dma_async_tx_descriptor *(*device_prep_dma_memcpy)(
		struct dma_chan *chan, dma_addr_t dest, dma_addr_t src,
		size_t len, unsigned long flags);
	struct dma_async_tx_descriptor *(*device_prep_dma_xor)(
		struct dma_chan *chan, dma_addr_t dest, dma_addr_t *src,
		unsigned int src_cnt, size_t len, unsigned long flags);
	struct dma_async_tx_descriptor *(*device_prep_dma_xor_val)(
		struct dma_chan *chan, dma_addr_t *src,	unsigned int src_cnt,
		size_t len, enum sum_check_flags *result, unsigned long flags);
	struct dma_async_tx_descriptor *(*device_prep_dma_pq)(
		struct dma_chan *chan, dma_addr_t *dst, dma_addr_t *src,
		unsigned int src_cnt, const unsigned char *scf,
		size_t len, unsigned long flags);
	struct dma_async_tx_descriptor *(*device_prep_dma_pq_val)(
		struct dma_chan *chan, dma_addr_t *pq, dma_addr_t *src,
		unsigned int src_cnt, const unsigned char *scf, size_t len,
		enum sum_check_flags *pqres, unsigned long flags);
	struct dma_async_tx_descriptor *(*device_prep_dma_memset)(
		struct dma_chan *chan, dma_addr_t dest, int value, size_t len,
		unsigned long flags);
	struct dma_async_tx_descriptor *(*device_prep_dma_interrupt)(
		struct dma_chan *chan, unsigned long flags);
	struct dma_async_tx_descriptor *(*device_prep_dma_sg)(
		struct dma_chan *chan,
		struct scatterlist *dst_sg, unsigned int dst_nents,
		struct scatterlist *src_sg, unsigned int src_nents,
		unsigned long flags);

	struct dma_async_tx_descriptor *(*device_prep_slave_sg)(
		struct dma_chan *chan, struct scatterlist *sgl,
		unsigned int sg_len, enum dma_transfer_direction direction,
		unsigned long flags, void *context);
	struct dma_async_tx_descriptor *(*device_prep_dma_cyclic)(
		struct dma_chan *chan, dma_addr_t buf_addr, size_t buf_len,
		size_t period_len, enum dma_transfer_direction direction,
		void *context);
	struct dma_async_tx_descriptor *(*device_prep_interleaved_dma)(
		struct dma_chan *chan, struct dma_interleaved_template *xt,
		unsigned long flags);
	int (*device_control)(struct dma_chan *chan, enum dma_ctrl_cmd cmd,
		unsigned long arg);

	enum dma_status (*device_tx_status)(struct dma_chan *chan,
					    dma_cookie_t cookie,
					    struct dma_tx_state *txstate);
	void (*device_issue_pending)(struct dma_chan *chan);
};

static inline int dmaengine_device_control(struct dma_chan *chan,
					   enum dma_ctrl_cmd cmd,
					   unsigned long arg)
{
	return chan->device->device_control(chan, cmd, arg);
}

static inline int dmaengine_slave_config(struct dma_chan *chan,
					  struct dma_slave_config *config)
{
	return dmaengine_device_control(chan, DMA_SLAVE_CONFIG,
			(unsigned long)config);
}

static inline struct dma_async_tx_descriptor *dmaengine_prep_slave_single(
	struct dma_chan *chan, void *buf, size_t len,
	enum dma_transfer_direction dir, unsigned long flags)
{
	struct scatterlist sg;
	sg_init_one(&sg, buf, len);

	return chan->device->device_prep_slave_sg(chan, &sg, 1,
						  dir, flags, NULL);
}

static inline struct dma_async_tx_descriptor *dmaengine_prep_slave_sg(
	struct dma_chan *chan, struct scatterlist *sgl,	unsigned int sg_len,
	enum dma_transfer_direction dir, unsigned long flags)
{
	return chan->device->device_prep_slave_sg(chan, sgl, sg_len,
						  dir, flags, NULL);
}

static inline struct dma_async_tx_descriptor *dmaengine_prep_dma_cyclic(
		struct dma_chan *chan, dma_addr_t buf_addr, size_t buf_len,
		size_t period_len, enum dma_transfer_direction dir)
{
	return chan->device->device_prep_dma_cyclic(chan, buf_addr, buf_len,
						period_len, dir, NULL);
}

static inline int dmaengine_terminate_all(struct dma_chan *chan)
{
	return dmaengine_device_control(chan, DMA_TERMINATE_ALL, 0);
}

static inline int dmaengine_pause(struct dma_chan *chan)
{
	return dmaengine_device_control(chan, DMA_PAUSE, 0);
}

static inline int dmaengine_resume(struct dma_chan *chan)
{
	return dmaengine_device_control(chan, DMA_RESUME, 0);
}

static inline dma_cookie_t dmaengine_submit(struct dma_async_tx_descriptor *desc)
{
	return desc->tx_submit(desc);
}

static inline bool dmaengine_check_align(u8 align, size_t off1, size_t off2, size_t len)
{
	size_t mask;

	if (!align)
		return true;
	mask = (1 << align) - 1;
	if (mask & (off1 | off2 | len))
		return false;
	return true;
}

static inline bool is_dma_copy_aligned(struct dma_device *dev, size_t off1,
				       size_t off2, size_t len)
{
	return dmaengine_check_align(dev->copy_align, off1, off2, len);
}

static inline bool is_dma_xor_aligned(struct dma_device *dev, size_t off1,
				      size_t off2, size_t len)
{
	return dmaengine_check_align(dev->xor_align, off1, off2, len);
}

static inline bool is_dma_pq_aligned(struct dma_device *dev, size_t off1,
				     size_t off2, size_t len)
{
	return dmaengine_check_align(dev->pq_align, off1, off2, len);
}

static inline bool is_dma_fill_aligned(struct dma_device *dev, size_t off1,
				       size_t off2, size_t len)
{
	return dmaengine_check_align(dev->fill_align, off1, off2, len);
}

static inline void
dma_set_maxpq(struct dma_device *dma, int maxpq, int has_pq_continue)
{
	dma->max_pq = maxpq;
	if (has_pq_continue)
		dma->max_pq |= DMA_HAS_PQ_CONTINUE;
}

static inline bool dmaf_continue(enum dma_ctrl_flags flags)
{
	return (flags & DMA_PREP_CONTINUE) == DMA_PREP_CONTINUE;
}

static inline bool dmaf_p_disabled_continue(enum dma_ctrl_flags flags)
{
	enum dma_ctrl_flags mask = DMA_PREP_CONTINUE | DMA_PREP_PQ_DISABLE_P;

	return (flags & mask) == mask;
}

static inline bool dma_dev_has_pq_continue(struct dma_device *dma)
{
	return (dma->max_pq & DMA_HAS_PQ_CONTINUE) == DMA_HAS_PQ_CONTINUE;
}

static inline unsigned short dma_dev_to_maxpq(struct dma_device *dma)
{
	return dma->max_pq & ~DMA_HAS_PQ_CONTINUE;
}

/* dma_maxpq - reduce maxpq in the face of continued operations
 * @dma - dma device with PQ capability
 * @flags - to check if DMA_PREP_CONTINUE and DMA_PREP_PQ_DISABLE_P are set
 *
 * When an engine does not support native continuation we need 3 extra
 * source slots to reuse P and Q with the following coefficients:
 * 1/ {00} * P : remove P from Q', but use it as a source for P'
 * 2/ {01} * Q : use Q to continue Q' calculation
 * 3/ {00} * Q : subtract Q from P' to cancel (2)
 *
 * In the case where P is disabled we only need 1 extra source:
 * 1/ {01} * Q : use Q to continue Q' calculation
 */
static inline int dma_maxpq(struct dma_device *dma, enum dma_ctrl_flags flags)
{
	if (dma_dev_has_pq_continue(dma) || !dmaf_continue(flags))
		return dma_dev_to_maxpq(dma);
	else if (dmaf_p_disabled_continue(flags))
		return dma_dev_to_maxpq(dma) - 1;
	else if (dmaf_continue(flags))
		return dma_dev_to_maxpq(dma) - 3;
	BUG();
}

/* --- public DMA engine API --- */

#ifdef CONFIG_DMA_ENGINE
void dmaengine_get(void);
void dmaengine_put(void);
#else
static inline void dmaengine_get(void)
{
}
static inline void dmaengine_put(void)
{
}
#endif

#ifdef CONFIG_NET_DMA
#define net_dmaengine_get()	dmaengine_get()
#define net_dmaengine_put()	dmaengine_put()
#else
static inline void net_dmaengine_get(void)
{
}
static inline void net_dmaengine_put(void)
{
}
#endif

#ifdef CONFIG_ASYNC_TX_DMA
#define async_dmaengine_get()	dmaengine_get()
#define async_dmaengine_put()	dmaengine_put()
#ifndef CONFIG_ASYNC_TX_ENABLE_CHANNEL_SWITCH
#define async_dma_find_channel(type) dma_find_channel(DMA_ASYNC_TX)
#else
#define async_dma_find_channel(type) dma_find_channel(type)
#endif /* CONFIG_ASYNC_TX_ENABLE_CHANNEL_SWITCH */
#else
static inline void async_dmaengine_get(void)
{
}
static inline void async_dmaengine_put(void)
{
}
static inline struct dma_chan *
async_dma_find_channel(enum dma_transaction_type type)
{
	return NULL;
}
#endif /* CONFIG_ASYNC_TX_DMA */

dma_cookie_t dma_async_memcpy_buf_to_buf(struct dma_chan *chan,
	void *dest, void *src, size_t len);
dma_cookie_t dma_async_memcpy_buf_to_pg(struct dma_chan *chan,
	struct page *page, unsigned int offset, void *kdata, size_t len);
dma_cookie_t dma_async_memcpy_pg_to_pg(struct dma_chan *chan,
	struct page *dest_pg, unsigned int dest_off, struct page *src_pg,
	unsigned int src_off, size_t len);
void dma_async_tx_descriptor_init(struct dma_async_tx_descriptor *tx,
	struct dma_chan *chan);

static inline void async_tx_ack(struct dma_async_tx_descriptor *tx)
{
	tx->flags |= DMA_CTRL_ACK;
}

static inline void async_tx_clear_ack(struct dma_async_tx_descriptor *tx)
{
	tx->flags &= ~DMA_CTRL_ACK;
}

static inline bool async_tx_test_ack(struct dma_async_tx_descriptor *tx)
{
	return (tx->flags & DMA_CTRL_ACK) == DMA_CTRL_ACK;
}

#define first_dma_cap(mask) __first_dma_cap(&(mask))
static inline int __first_dma_cap(const dma_cap_mask_t *srcp)
{
	return min_t(int, DMA_TX_TYPE_END,
		find_first_bit(srcp->bits, DMA_TX_TYPE_END));
}

#define next_dma_cap(n, mask) __next_dma_cap((n), &(mask))
static inline int __next_dma_cap(int n, const dma_cap_mask_t *srcp)
{
	return min_t(int, DMA_TX_TYPE_END,
		find_next_bit(srcp->bits, DMA_TX_TYPE_END, n+1));
}

#define dma_cap_set(tx, mask) __dma_cap_set((tx), &(mask))
static inline void
__dma_cap_set(enum dma_transaction_type tx_type, dma_cap_mask_t *dstp)
{
	set_bit(tx_type, dstp->bits);
}

#define dma_cap_clear(tx, mask) __dma_cap_clear((tx), &(mask))
static inline void
__dma_cap_clear(enum dma_transaction_type tx_type, dma_cap_mask_t *dstp)
{
	clear_bit(tx_type, dstp->bits);
}

#define dma_cap_zero(mask) __dma_cap_zero(&(mask))
static inline void __dma_cap_zero(dma_cap_mask_t *dstp)
{
	bitmap_zero(dstp->bits, DMA_TX_TYPE_END);
}

#define dma_has_cap(tx, mask) __dma_has_cap((tx), &(mask))
static inline int
__dma_has_cap(enum dma_transaction_type tx_type, dma_cap_mask_t *srcp)
{
	return test_bit(tx_type, srcp->bits);
}

#define for_each_dma_cap_mask(cap, mask) \
	for ((cap) = first_dma_cap(mask);	\
		(cap) < DMA_TX_TYPE_END;	\
		(cap) = next_dma_cap((cap), (mask)))

/**
 * dma_async_issue_pending - flush pending transactions to HW
 * @chan: target DMA channel
 *
 * This allows drivers to push copies to HW in batches,
 * reducing MMIO writes where possible.
 */
static inline void dma_async_issue_pending(struct dma_chan *chan)
{
	chan->device->device_issue_pending(chan);
}

#define dma_async_memcpy_issue_pending(chan) dma_async_issue_pending(chan)

/**
 * dma_async_is_tx_complete - poll for transaction completion
 * @chan: DMA channel
 * @cookie: transaction identifier to check status of
 * @last: returns last completed cookie, can be NULL
 * @used: returns last issued cookie, can be NULL
 *
 * If @last and @used are passed in, upon return they reflect the driver
 * internal state and can be used with dma_async_is_complete() to check
 * the status of multiple cookies without re-checking hardware state.
 */
static inline enum dma_status dma_async_is_tx_complete(struct dma_chan *chan,
	dma_cookie_t cookie, dma_cookie_t *last, dma_cookie_t *used)
{
	struct dma_tx_state state;
	enum dma_status status;

	status = chan->device->device_tx_status(chan, cookie, &state);
	if (last)
		*last = state.last;
	if (used)
		*used = state.used;
	return status;
}

#define dma_async_memcpy_complete(chan, cookie, last, used)\
	dma_async_is_tx_complete(chan, cookie, last, used)

/**
 * dma_async_is_complete - test a cookie against chan state
 * @cookie: transaction identifier to test status of
 * @last_complete: last know completed transaction
 * @last_used: last cookie value handed out
 *
 * dma_async_is_complete() is used in dma_async_memcpy_complete()
 * the test logic is separated for lightweight testing of multiple cookies
 */
static inline enum dma_status dma_async_is_complete(dma_cookie_t cookie,
			dma_cookie_t last_complete, dma_cookie_t last_used)
{
	if (last_complete <= last_used) {
		if ((cookie <= last_complete) || (cookie > last_used))
			return DMA_SUCCESS;
	} else {
		if ((cookie <= last_complete) && (cookie > last_used))
			return DMA_SUCCESS;
	}
	return DMA_IN_PROGRESS;
}

static inline void
dma_set_tx_state(struct dma_tx_state *st, dma_cookie_t last, dma_cookie_t used, u32 residue)
{
	if (st) {
		st->last = last;
		st->used = used;
		st->residue = residue;
	}
}

enum dma_status dma_sync_wait(struct dma_chan *chan, dma_cookie_t cookie);
#ifdef CONFIG_DMA_ENGINE
enum dma_status dma_wait_for_async_tx(struct dma_async_tx_descriptor *tx);
void dma_issue_pending_all(void);
struct dma_chan *__dma_request_channel(dma_cap_mask_t *mask, dma_filter_fn fn, void *fn_param);
void dma_release_channel(struct dma_chan *chan);
#else
static inline enum dma_status dma_wait_for_async_tx(struct dma_async_tx_descriptor *tx)
{
	return DMA_SUCCESS;
}
static inline void dma_issue_pending_all(void)
{
}
static inline struct dma_chan *__dma_request_channel(dma_cap_mask_t *mask,
					      dma_filter_fn fn, void *fn_param)
{
	return NULL;
}
static inline void dma_release_channel(struct dma_chan *chan)
{
}
#endif

/* --- DMA device --- */

int dma_async_device_register(struct dma_device *device);
void dma_async_device_unregister(struct dma_device *device);
void dma_run_dependencies(struct dma_async_tx_descriptor *tx);
struct dma_chan *dma_find_channel(enum dma_transaction_type tx_type);
struct dma_chan *net_dma_find_channel(void);
#define dma_request_channel(mask, x, y) __dma_request_channel(&(mask), x, y)

/* --- Helper iov-locking functions --- */

struct dma_page_list {
	char __user *base_address;
	int nr_pages;
	struct page **pages;
};

struct dma_pinned_list {
	int nr_iovecs;
	struct dma_page_list page_list[0];
};

struct dma_pinned_list *dma_pin_iovec_pages(struct iovec *iov, size_t len);
void dma_unpin_iovec_pages(struct dma_pinned_list* pinned_list);

dma_cookie_t dma_memcpy_to_iovec(struct dma_chan *chan, struct iovec *iov,
	struct dma_pinned_list *pinned_list, unsigned char *kdata, size_t len);
dma_cookie_t dma_memcpy_pg_to_iovec(struct dma_chan *chan, struct iovec *iov,
	struct dma_pinned_list *pinned_list, struct page *page,
	unsigned int offset, size_t len);

#endif /* DMAENGINE_H */


text:
package com.kynerix.server.rules.conditions;

import com.kynerix.server.rules.LogRule;
import com.kynerix.server.rules.RuleConditionEvaluator;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * Base class for implementing conditions
 */
public abstract class BaseCondition implements RuleConditionEvaluator {

    protected Logger logger = LogManager.getLogger(this.getClass());

    protected void checkLog(LogRule ruleInstance) {
        assert ruleInstance.getOperator().equals(getKey());
        assert ruleInstance.getField() != null;
    }

    @Override
    public boolean validate(LogRule rule) {
        if (!rule.getOperator().equals(getKey())) {
            logger.error("Operator key does not match " + getKey() + " for rule " + rule);
            return false;
        }

        if (rule.getField() == null) {
            logger.error("Field is not defined: " + rule);
        }

        return rule.getOperatorArg1() != null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.calcite.test;

import org.apache.calcite.adapter.enumerable.EnumerableConvention;
import org.apache.calcite.adapter.enumerable.EnumerableHashJoin;
import org.apache.calcite.adapter.enumerable.EnumerableRules;
import org.apache.calcite.plan.Convention;
import org.apache.calcite.plan.RelOptCluster;
import org.apache.calcite.plan.RelOptRuleCall;
import org.apache.calcite.plan.RelOptUtil;
import org.apache.calcite.plan.RelRule;
import org.apache.calcite.plan.hep.HepPlanner;
import org.apache.calcite.plan.hep.HepProgram;
import org.apache.calcite.plan.hep.HepProgramBuilder;
import org.apache.calcite.plan.volcano.AbstractConverter;
import org.apache.calcite.rel.RelCollationTraitDef;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.RelShuttleImpl;
import org.apache.calcite.rel.RelVisitor;
import org.apache.calcite.rel.convert.ConverterRule;
import org.apache.calcite.rel.core.Aggregate;
import org.apache.calcite.rel.core.Calc;
import org.apache.calcite.rel.core.Filter;
import org.apache.calcite.rel.core.Join;
import org.apache.calcite.rel.core.JoinInfo;
import org.apache.calcite.rel.core.Snapshot;
import org.apache.calcite.rel.core.TableScan;
import org.apache.calcite.rel.core.Window;
import org.apache.calcite.rel.hint.HintPredicate;
import org.apache.calcite.rel.hint.HintPredicates;
import org.apache.calcite.rel.hint.HintStrategy;
import org.apache.calcite.rel.hint.HintStrategyTable;
import org.apache.calcite.rel.hint.Hintable;
import org.apache.calcite.rel.hint.RelHint;
import org.apache.calcite.rel.logical.LogicalAggregate;
import org.apache.calcite.rel.logical.LogicalCorrelate;
import org.apache.calcite.rel.logical.LogicalFilter;
import org.apache.calcite.rel.logical.LogicalIntersect;
import org.apache.calcite.rel.logical.LogicalJoin;
import org.apache.calcite.rel.logical.LogicalMinus;
import org.apache.calcite.rel.logical.LogicalProject;
import org.apache.calcite.rel.logical.LogicalSort;
import org.apache.calcite.rel.logical.LogicalUnion;
import org.apache.calcite.rel.logical.LogicalValues;
import org.apache.calcite.rel.rules.CoreRules;
import org.apache.calcite.sql.SqlDelete;
import org.apache.calcite.sql.SqlInsert;
import org.apache.calcite.sql.SqlMerge;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.SqlTableRef;
import org.apache.calcite.sql.SqlUpdate;
import org.apache.calcite.sql.SqlUtil;
import org.apache.calcite.sql.test.SqlTestFactory;
import org.apache.calcite.sql.test.SqlTester;
import org.apache.calcite.tools.RuleSet;
import org.apache.calcite.tools.RuleSets;
import org.apache.calcite.util.Litmus;
import org.apache.calcite.util.Util;

import org.checkerframework.checker.nullness.qual.Nullable;
import org.immutables.value.Value;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.apache.calcite.test.Matchers.relIsValid;
import static org.apache.calcite.test.SqlToRelTestBase.NL;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIn.in;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;

import static java.util.Objects.requireNonNull;

/**
 * Unit test for {@link org.apache.calcite.rel.hint.RelHint}.
 */
class SqlHintsConverterTest {

  static final Fixture FIXTURE =
      new Fixture(SqlTestFactory.INSTANCE,
          DiffRepository.lookup(SqlHintsConverterTest.class),
          "?", false, false)
          .withFactory(f ->
              f.withSqlToRelConfig(c ->
                  c.withHintStrategyTable(HintTools.HINT_STRATEGY_TABLE)));

  static final RelOptFixture RULE_FIXTURE =
      RelOptFixture.DEFAULT
          .withDiffRepos(DiffRepository.lookup(SqlHintsConverterTest.class))
          .withConfig(c ->
              c.withHintStrategyTable(HintTools.HINT_STRATEGY_TABLE));

  protected Fixture fixture() {
    return FIXTURE;
  }

  protected RelOptFixture ruleFixture() {
    return RULE_FIXTURE;
  }

  /** Sets the SQL statement for a test. */
  public final Fixture sql(String sql) {
    return fixture().sql(sql);
  }

  //~ Tests ------------------------------------------------------------------

  @Test void testQueryHint() {
    final String sql = HintTools.withHint("select /*+ %s */ *\n"
        + "from emp e1\n"
        + "inner join dept d1 on e1.deptno = d1.deptno\n"
        + "inner join emp e2 on e1.ename = e2.job");
    sql(sql).ok();
  }

  @Test void testQueryHintWithLiteralOptions() {
    final String sql = "select /*+ time_zone(1, 1.23, 'a bc', -1.0) */ *\n"
        + "from emp";
    sql(sql).ok();
  }

  @Test void testNestedQueryHint() {
    final String sql = "select /*+ resource(parallelism='3'), repartition(10) */ empno\n"
        + "from (select /*+ resource(mem='20Mb')*/ empno, ename from emp)";
    sql(sql).ok();
  }

  @Test void testTwoLevelNestedQueryHint() {
    final String sql = "select /*+ resource(parallelism='3'), no_hash_join */ empno\n"
        + "from (select /*+ resource(mem='20Mb')*/ empno, ename\n"
        + "from emp left join dept on emp.deptno = dept.deptno)";
    sql(sql).ok();
  }

  @Test void testThreeLevelNestedQueryHint() {
    final String sql = "select /*+ index(idx1), no_hash_join */ * from emp /*+ index(empno) */\n"
        + "e1 join dept/*+ index(deptno) */ d1 on e1.deptno = d1.deptno\n"
        + "join emp e2 on d1.name = e2.job";
    sql(sql).ok();
  }

  @Test void testFourLevelNestedQueryHint() {
    final String sql = "select /*+ index(idx1), no_hash_join */ * from emp /*+ index(empno) */\n"
        + "e1 join dept/*+ index(deptno) */ d1 on e1.deptno = d1.deptno join\n"
        + "(select max(sal) as sal from emp /*+ index(empno) */) e2 on e1.sal = e2.sal";
    sql(sql).ok();
  }

  @Test void testAggregateHints() {
    final String sql = "select /*+ AGG_STRATEGY(TWO_PHASE), RESOURCE(mem='1024') */\n"
        + "count(deptno), avg_sal from (\n"
        + "select /*+ AGG_STRATEGY(ONE_PHASE) */ avg(sal) as avg_sal, deptno\n"
        + "from emp group by deptno) group by avg_sal";
    sql(sql).ok();
  }

  @Test void testCorrelateHints() {
    final String sql = "select /*+ use_hash_join (orders, products_temporal) */ stream *\n"
        + "from orders join products_temporal for system_time as of orders.rowtime\n"
        + "on orders.productid = products_temporal.productid and orders.orderId is not null";
    sql(sql).ok();
  }

  @Test void testCrossCorrelateHints() {
    final String sql = "select /*+ use_hash_join (orders, products_temporal) */ stream *\n"
        + "from orders, products_temporal for system_time as of orders.rowtime";
    sql(sql).ok();
  }

  @Test void testFilterHints() {
    final String sql = "select /*+ resource(parallelism='3') */ avg(sal) as avg_sal, deptno\n"
            + "from emp group by deptno having avg(sal) > 5000";
    sql(sql).ok();
  }

  @Test void testUnionHints() {
    final String sql = "select /*+ breakable */ deptno from\n"
            + "(select ename, deptno from emp\n"
            + "union all\n"
            + "select name, deptno from dept)";
    sql(sql).ok();
  }

  @Test void testMinusHints() {
    final String sql = "select /*+ breakable */ deptno from\n"
        + "(select ename, deptno from emp\n"
        + "except all\n"
        + "select name, deptno from dept)";
    sql(sql).ok();
  }

  @Test void testIntersectHints() {
    final String sql = "select /*+ breakable */ deptno from\n"
        + "(select ename, deptno from emp\n"
        + "intersect all\n"
        + "select name, deptno from dept)";
    sql(sql).ok();
  }

  @Test void testSortHints() {
    final String sql = "select /*+ async_merge */ empno from emp order by empno, empno desc";
    sql(sql).ok();
  }

  @Test void testValuesHints() {
    final String sql = "select /*+ resource(parallelism='3') */ a, max(b), max(b + 1)\n"
        + "from (values (1, 2)) as t(a, b)\n"
        + "group by a";
    sql(sql).ok();
  }

  @Test void testWindowHints() {
    final String sql = "select /*+ mini_batch */ last_value(deptno)\n"
        + "over (order by empno rows 2 following) from emp";
    sql(sql).ok();
  }

  @Test void testSnapshotHints() {
    final String sql = "select /*+ fast_snapshot(products_temporal) */ stream * from\n"
        + " orders join products_temporal for system_time as of timestamp '2022-08-11 15:00:00'\n"
        + " on orders.productid = products_temporal.productid";
    sql(sql).ok();
  }

  @Test void testHintsInSubQueryWithDecorrelation() {
    final String sql = "select /*+ resource(parallelism='3'), AGG_STRATEGY(TWO_PHASE) */\n"
        + "sum(e1.empno) from emp e1, dept d1\n"
        + "where e1.deptno = d1.deptno\n"
        + "and e1.sal> (\n"
        + "select /*+ resource(cpu='2') */ avg(e2.sal) from emp e2 where e2.deptno = d1.deptno)";
    sql(sql).withDecorrelate(true).ok();
  }

  @Test void testHintsInSubQueryWithDecorrelation2() {
    final String sql = "select /*+ properties(k1='v1', k2='v2'), index(ename), no_hash_join */\n"
        + "sum(e1.empno) from emp e1, dept d1\n"
        + "where e1.deptno = d1.deptno\n"
        + "and e1.sal> (\n"
        + "select /*+ properties(k1='v1', k2='v2'), index(ename), no_hash_join */\n"
        + "  avg(e2.sal)\n"
        + "  from emp e2\n"
        + "  where e2.deptno = d1.deptno)";
    sql(sql).withDecorrelate(true).ok();
  }

  @Test void testHintsInSubQueryWithDecorrelation3() {
    final String sql = "select /*+ resource(parallelism='3'), index(ename), no_hash_join */\n"
        + "sum(e1.empno) from emp e1, dept d1\n"
        + "where e1.deptno = d1.deptno\n"
        + "and e1.sal> (\n"
        + "select /*+ resource(cpu='2'), index(ename), no_hash_join */\n"
        + "  avg(e2.sal)\n"
        + "  from emp e2\n"
        + "  where e2.deptno = d1.deptno)";
    sql(sql).withDecorrelate(true).ok();
  }

  @Test void testHintsInSubQueryWithoutDecorrelation() {
    final String sql = "select /*+ resource(parallelism='3') */\n"
        + "sum(e1.empno) from emp e1, dept d1\n"
        + "where e1.deptno = d1.deptno\n"
        + "and e1.sal> (\n"
        + "select /*+ resource(cpu='2') */ avg(e2.sal) from emp e2 where e2.deptno = d1.deptno)";
    sql(sql).ok();
  }

  @Test void testInvalidQueryHint() {
    final String sql = "select /*+ weird_hint */ empno\n"
        + "from (select /*+ resource(mem='20Mb')*/ empno, ename\n"
        + "from emp left join dept on emp.deptno = dept.deptno)";
    sql(sql).warns("Hint: WEIRD_HINT should be registered in the HintStrategyTable");

    final String sql1 = "select /*+ resource(mem='20Mb')*/ empno\n"
        + "from (select /*+ weird_kv_hint(k1='v1') */ empno, ename\n"
        + "from emp left join dept on emp.deptno = dept.deptno)";
    sql(sql1).warns("Hint: WEIRD_KV_HINT should be registered in the HintStrategyTable");

    final String sql2 = "select /*+ AGG_STRATEGY(OPTION1) */\n"
        + "ename, avg(sal)\n"
        + "from emp group by ename";
    final String error2 = "Hint AGG_STRATEGY only allows single option, "
        + "allowed options: [ONE_PHASE, TWO_PHASE]";
    sql(sql2).warns(error2);
    // Change the error handler to validate again.
    sql(sql2).withFactory(f ->
        f.withSqlToRelConfig(c ->
            c.withHintStrategyTable(
                HintTools.createHintStrategies(
                    HintStrategyTable.builder().errorHandler(Litmus.THROW)))))
        .fails(error2);
  }

  @Test void testTableHintsInJoin() {
    final String sql = "select\n"
        + "ename, job, sal, dept.name\n"
        + "from emp /*+ index(idx1, idx2) */\n"
        + "join dept /*+ properties(k1='v1', k2='v2') */\n"
        + "on emp.deptno = dept.deptno";
    sql(sql).ok();
  }

  @Test void testTableHintsInSelect() {
    final String sql = HintTools.withHint("select * from emp /*+ %s */");
    sql(sql).ok();
  }

  @Test void testSameHintsWithDifferentInheritPath() {
    final String sql = "select /*+ properties(k1='v1', k2='v2') */\n"
        + "ename, job, sal, dept.name\n"
        + "from emp /*+ index(idx1, idx2) */\n"
        + "join dept /*+ properties(k1='v1', k2='v2') */\n"
        + "on emp.deptno = dept.deptno";
    sql(sql).ok();
  }

  @Test void testTableHintsInInsert() throws Exception {
    final String sql = HintTools.withHint("insert into dept /*+ %s */ (deptno, name) "
        + "select deptno, name from dept");
    final SqlInsert insert = (SqlInsert) sql(sql).parseQuery();
    assert insert.getTargetTable() instanceof SqlTableRef;
    final SqlTableRef tableRef = (SqlTableRef) insert.getTargetTable();
    List<RelHint> hints = SqlUtil.getRelHint(HintTools.HINT_STRATEGY_TABLE,
        (SqlNodeList) tableRef.getOperandList().get(1));
    assertHintsEquals(
        Arrays.asList(
          HintTools.PROPS_HINT,
          HintTools.IDX_HINT,
          HintTools.JOIN_HINT),
        hints);
  }

  @Test void testTableHintsInUpdate() throws Exception {
    final String sql = HintTools.withHint("update emp /*+ %s */ "
        + "set name = 'test' where deptno = 1");
    final SqlUpdate sqlUpdate = (SqlUpdate) sql(sql).parseQuery();
    assert sqlUpdate.getTargetTable() instanceof SqlTableRef;
    final SqlTableRef tableRef = (SqlTableRef) sqlUpdate.getTargetTable();
    List<RelHint> hints = SqlUtil.getRelHint(HintTools.HINT_STRATEGY_TABLE,
        (SqlNodeList) tableRef.getOperandList().get(1));
    assertHintsEquals(
        Arrays.asList(
          HintTools.PROPS_HINT,
          HintTools.IDX_HINT,
          HintTools.JOIN_HINT),
        hints);
  }

  @Test void testTableHintsInDelete() throws Exception {
    final String sql = HintTools.withHint("delete from emp /*+ %s */ where deptno = 1");
    final SqlDelete sqlDelete = (SqlDelete) sql(sql).parseQuery();
    assert sqlDelete.getTargetTable() instanceof SqlTableRef;
    final SqlTableRef tableRef = (SqlTableRef) sqlDelete.getTargetTable();
    List<RelHint> hints = SqlUtil.getRelHint(HintTools.HINT_STRATEGY_TABLE,
        (SqlNodeList) tableRef.getOperandList().get(1));
    assertHintsEquals(
        Arrays.asList(
          HintTools.PROPS_HINT,
          HintTools.IDX_HINT,
          HintTools.JOIN_HINT),
        hints);
  }

  @Test void testTableHintsInMerge() throws Exception {
    final String sql = "merge into emps\n"
        + "/*+ %s */ e\n"
        + "using tempemps as t\n"
        + "on e.empno = t.empno\n"
        + "when matched then update\n"
        + "set name = t.name, deptno = t.deptno, salary = t.salary * .1\n"
        + "when not matched then insert (name, dept, salary)\n"
        + "values(t.name, 10, t.salary * .15)";
    final String sql1 = HintTools.withHint(sql);

    final SqlMerge sqlMerge = (SqlMerge) sql(sql1).parseQuery();
    assert sqlMerge.getTargetTable() instanceof SqlTableRef;
    final SqlTableRef tableRef = (SqlTableRef) sqlMerge.getTargetTable();
    List<RelHint> hints = SqlUtil.getRelHint(HintTools.HINT_STRATEGY_TABLE,
        (SqlNodeList) tableRef.getOperandList().get(1));
    assertHintsEquals(
        Arrays.asList(
            HintTools.PROPS_HINT,
            HintTools.IDX_HINT,
            HintTools.JOIN_HINT),
        hints);
  }

  @Test void testInvalidTableHints() {
    final String sql = "select\n"
        + "ename, job, sal, dept.name\n"
        + "from emp /*+ weird_hint(idx1, idx2) */\n"
        + "join dept /*+ properties(k1='v1', k2='v2') */\n"
        + "on emp.deptno = dept.deptno";
    sql(sql).warns("Hint: WEIRD_HINT should be registered in the HintStrategyTable");

    final String sql1 = "select\n"
        + "ename, job, sal, dept.name\n"
        + "from emp /*+ index(idx1, idx2) */\n"
        + "join dept /*+ weird_kv_hint(k1='v1', k2='v2') */\n"
        + "on emp.deptno = dept.deptno";
    sql(sql1).warns("Hint: WEIRD_KV_HINT should be registered in the HintStrategyTable");
  }

  @Test void testJoinHintRequiresSpecificInputs() {
    final String sql = "select /*+ use_hash_join(r, s), use_hash_join(emp, dept) */\n"
        + "ename, job, sal, dept.name\n"
        + "from emp join dept on emp.deptno = dept.deptno";
    // Hint use_hash_join(r, s) expect to be ignored by the join node.
    sql(sql).ok();
  }

  @Test void testHintsForCalc() {
    final String sql = "select /*+ resource(mem='1024MB')*/ ename, sal, deptno from emp";
    final RelNode rel = sql(sql).toRel();
    final RelHint hint = RelHint.builder("RESOURCE")
        .hintOption("MEM", "1024MB")
        .build();
    // planner rule to convert Project to Calc.
    HepProgram program = new HepProgramBuilder()
        .addRuleInstance(CoreRules.PROJECT_TO_CALC)
        .build();
    HepPlanner planner = new HepPlanner(program);
    planner.setRoot(rel);
    RelNode newRel = planner.findBestExp();
    new ValidateHintVisitor(hint, Calc.class).go(newRel);
  }

  @Test void testHintsPropagationInHepPlannerRules() {
    final String sql = "select /*+ use_hash_join(r, s), use_hash_join(emp, dept) */\n"
        + "ename, job, sal, dept.name\n"
        + "from emp join dept on emp.deptno = dept.deptno";
    final RelNode rel = sql(sql).toRel();
    final RelHint hint = RelHint.builder("USE_HASH_JOIN")
        .inheritPath(0)
        .hintOption("EMP")
        .hintOption("DEPT")
        .build();
    // Validate Hep planner.
    HepProgram program = new HepProgramBuilder()
        .addRuleInstance(MockJoinRule.INSTANCE)
        .build();
    HepPlanner planner = new HepPlanner(program);
    planner.setRoot(rel);
    RelNode newRel = planner.findBestExp();
    new ValidateHintVisitor(hint, Join.class).go(newRel);
  }

  @Test void testHintsPropagationInVolcanoPlannerRules() {
    final String sql = "select /*+ use_hash_join(r, s), use_hash_join(emp, dept) */\n"
        + "ename, job, sal, dept.name\n"
        + "from emp join dept on emp.deptno = dept.deptno";
    final RelHint hint = RelHint.builder("USE_HASH_JOIN")
        .inheritPath(0)
        .hintOption("EMP")
        .hintOption("DEPT")
        .build();
    // Validate Volcano planner.
    RuleSet ruleSet = RuleSets.ofList(
        MockEnumerableJoinRule.create(hint), // Rule to validate the hint.
        CoreRules.FILTER_PROJECT_TRANSPOSE,
        CoreRules.FILTER_MERGE,
        CoreRules.PROJECT_MERGE,
        EnumerableRules.ENUMERABLE_JOIN_RULE,
        EnumerableRules.ENUMERABLE_PROJECT_RULE,
        EnumerableRules.ENUMERABLE_FILTER_RULE,
        EnumerableRules.ENUMERABLE_SORT_RULE,
        EnumerableRules.ENUMERABLE_LIMIT_RULE,
        EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE);
    ruleFixture()
        .sql(sql)
        .withVolcanoPlanner(false, p -> {
          p.addRelTraitDef(RelCollationTraitDef.INSTANCE);
          RelOptUtil.registerDefaultRules(p, false, false);
          ruleSet.forEach(p::addRule);
        })
        .check();
  }

  @Test void testHintsPropagationInVolcanoPlannerRules2() {
    final String sql = "select /*+ no_hash_join */ ename, job\n"
        + "from emp where not exists (select 1 from dept where emp.deptno = dept.deptno)";
    final RelHint hint = RelHint.builder("NO_HASH_JOIN")
        .inheritPath(0, 0)
        .build();
    // Validate Volcano planner.
    RuleSet ruleSet = RuleSets.ofList(
        MockEnumerableJoinRule.create(hint) // Rule to validate the hint.
    );
    ruleFixture()
        .sql(sql)
        .withTrim(true)
        .withVolcanoPlanner(false, p -> {
          p.addRelTraitDef(RelCollationTraitDef.INSTANCE);
          RelOptUtil.registerDefaultRules(p, false, false);
          ruleSet.forEach(p::addRule);
        })
        .check();
  }

  @Test void testHintsPropagationInVolcanoPlannerRules3() {
    final String sql = "select /*+ no_hash_join */ ename, job\n"
        + "from emp where not exists (select 1 from dept where emp.deptno = dept.deptno) order by ename";
    final RelHint hint = RelHint.builder("NO_HASH_JOIN")
        .inheritPath(0, 0, 0)
        .build();
    // Validate Volcano planner.
    RuleSet ruleSet = RuleSets.ofList(
        MockEnumerableJoinRule.create(hint) // Rule to validate the hint.
    );
    ruleFixture()
        .sql(sql)
        .withTrim(true)
        .withVolcanoPlanner(false, p -> {
          p.addRelTraitDef(RelCollationTraitDef.INSTANCE);
          RelOptUtil.registerDefaultRules(p, false, false);
          ruleSet.forEach(p::addRule);
        })
        .check();
  }

  @Test void testHintsPropagateWithDifferentKindOfRels() {
    final String sql = "select /*+ AGG_STRATEGY(TWO_PHASE) */\n"
        + "ename, avg(sal)\n"
        + "from emp group by ename";
    final RelNode rel = sql(sql).toRel();
    final RelHint hint = RelHint.builder("AGG_STRATEGY")
        .inheritPath(0)
        .hintOption("TWO_PHASE")
        .build();
    // AggregateReduceFunctionsRule does the transformation:
    // AGG -> PROJECT + AGG
    HepProgram program = new HepProgramBuilder()
        .addRuleInstance(CoreRules.AGGREGATE_REDUCE_FUNCTIONS)
        .build();
    HepPlanner planner = new HepPlanner(program);
    planner.setRoot(rel);
    RelNode newRel = planner.findBestExp();
    new ValidateHintVisitor(hint, Aggregate.class).go(newRel);
  }

  @Test void testUseMergeJoin() {
    final String sql = "select /*+ use_merge_join(emp, dept) */\n"
        + "ename, job, sal, dept.name\n"
        + "from emp join dept on emp.deptno = dept.deptno";
    RuleSet ruleSet = RuleSets.ofList(
        EnumerableRules.ENUMERABLE_MERGE_JOIN_RULE,
        EnumerableRules.ENUMERABLE_JOIN_RULE,
        EnumerableRules.ENUMERABLE_PROJECT_RULE,
        EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE,
        EnumerableRules.ENUMERABLE_SORT_RULE,
        AbstractConverter.ExpandConversionRule.INSTANCE);

    ruleFixture()
        .sql(sql)
        .withVolcanoPlanner(false, planner -> {
          planner.addRelTraitDef(RelCollationTraitDef.INSTANCE);
          ruleSet.forEach(planner::addRule);
        })
        .check();
  }

  //~ Methods ----------------------------------------------------------------

  private static boolean equalsStringList(List<String> l, List<String> r) {
    if (l.size() != r.size()) {
      return false;
    }
    for (String s : l) {
      if (!r.contains(s)) {
        return false;
      }
    }
    return true;
  }

  private static void assertHintsEquals(List<RelHint> expected, List<RelHint> actual) {
    assertArrayEquals(expected.toArray(new RelHint[0]), actual.toArray(new RelHint[0]));
  }

  //~ Inner Class ------------------------------------------------------------

  /** A Mock rule to validate the hint. */
  public static class MockJoinRule extends RelRule<MockJoinRule.Config> {
    public static final MockJoinRule INSTANCE = ImmutableMockJoinRuleConfig.builder()
        .build()
        .withOperandSupplier(b ->
            b.operand(LogicalJoin.class).anyInputs())
        .withDescription("MockJoinRule")
        .as(Config.class)
        .toRule();

    MockJoinRule(Config config) {
      super(config);
    }

    @Override public void onMatch(RelOptRuleCall call) {
      LogicalJoin join = call.rel(0);
      assertThat(join.getHints().size(), is(1));
      call.transformTo(
          LogicalJoin.create(join.getLeft(),
              join.getRight(),
              join.getHints(),
              join.getCondition(),
              join.getVariablesSet(),
              join.getJoinType()));
    }

    /** Rule configuration. */
    @Value.Immutable
    @Value.Style(typeImmutable = "ImmutableMockJoinRuleConfig")
    public interface Config extends RelRule.Config {
      @Override default MockJoinRule toRule() {
        return new MockJoinRule(this);
      }
    }
  }

  /** A Mock rule to validate the hint.
   * This rule also converts the rel to EnumerableConvention. */
  private static class MockEnumerableJoinRule extends ConverterRule {
    static MockEnumerableJoinRule create(RelHint hint) {
      return Config.INSTANCE
          .withConversion(LogicalJoin.class, Convention.NONE,
              EnumerableConvention.INSTANCE, "MockEnumerableJoinRule")
          .withRuleFactory(c -> new MockEnumerableJoinRule(c, hint))
          .toRule(MockEnumerableJoinRule.class);
    }

    MockEnumerableJoinRule(Config config, RelHint hint) {
      super(config);
      this.expectedHint = hint;
    }

    private final RelHint expectedHint;

    @Override public RelNode convert(RelNode rel) {
      LogicalJoin join = (LogicalJoin) rel;
      assertThat(join.getHints().size(), is(1));
      assertThat(join.getHints().get(0), is(expectedHint));
      List<RelNode> newInputs = new ArrayList<>();
      for (RelNode input : join.getInputs()) {
        if (!(input.getConvention() instanceof EnumerableConvention)) {
          input =
            convert(
              input,
              input.getTraitSet()
                .replace(EnumerableConvention.INSTANCE));
        }
        newInputs.add(input);
      }
      final RelOptCluster cluster = join.getCluster();
      final RelNode left = newInputs.get(0);
      final RelNode right = newInputs.get(1);
      final JoinInfo info = join.analyzeCondition();
      return EnumerableHashJoin.create(
        left,
        right,
        info.getEquiCondition(left, right, cluster.getRexBuilder()),
        join.getVariablesSet(),
        join.getJoinType());
    }
  }

  /** A visitor to validate a hintable node has specific hint. **/
  private static class ValidateHintVisitor extends RelVisitor {
    private final RelHint expectedHint;
    private final Class<?> clazz;

    /**
     * Creates the validate visitor.
     *
     * @param hint  the hint to validate
     * @param clazz the node type to validate the hint with
     */
    ValidateHintVisitor(RelHint hint, Class<?> clazz) {
      this.expectedHint = hint;
      this.clazz = clazz;
    }

    @Override public void visit(
        RelNode node,
        int ordinal,
        @Nullable RelNode parent) {
      if (clazz.isInstance(node)) {
        Hintable rel = (Hintable) node;
        assertThat(rel.getHints().size(), is(1));
        assertThat(rel.getHints().get(0), is(expectedHint));
      }
      super.visit(node, ordinal, parent);
    }
  }

  /** Test fixture. */
  private static class Fixture {
    private final String sql;
    private final DiffRepository diffRepos;
    private final SqlTestFactory factory;
    private final SqlTester tester = SqlToRelFixture.TESTER;
    private final List<String> hintsCollect = new ArrayList<>();
    private final boolean decorrelate;
    private final boolean trim;

    Fixture(SqlTestFactory factory, DiffRepository diffRepos, String sql,
        boolean decorrelate, boolean trim) {
      this.factory = requireNonNull(factory, "factory");
      this.sql = requireNonNull(sql, "sql");
      this.diffRepos = requireNonNull(diffRepos, "diffRepos");
      this.decorrelate = decorrelate;
      this.trim = trim;
    }

    Fixture sql(String sql) {
      return new Fixture(factory, diffRepos, sql, decorrelate, trim);
    }

    /** Creates a new Sql instance with new factory
     * applied with the {@code transform}. */
    Fixture withFactory(UnaryOperator<SqlTestFactory> transform) {
      final SqlTestFactory factory = transform.apply(this.factory);
      return new Fixture(factory, diffRepos, sql, decorrelate, trim);
    }

    Fixture withDecorrelate(boolean decorrelate) {
      return new Fixture(factory, diffRepos, sql, decorrelate, trim);
    }

    void ok() {
      assertHintsEquals(sql, "${hints}");
    }

    private void assertHintsEquals(
        String sql,
        String hint) {
      diffRepos.assertEquals("sql", "${sql}", sql);
      String sql2 = diffRepos.expand("sql", sql);
      final RelNode rel =
          tester.convertSqlToRel(factory, sql2, decorrelate, trim)
              .project();

      assertNotNull(rel);
      assertThat(rel, relIsValid());

      final HintCollector collector = new HintCollector(hintsCollect);
      rel.accept(collector);
      StringBuilder builder = new StringBuilder(NL);
      for (String hintLine : hintsCollect) {
        builder.append(hintLine).append(NL);
      }
      diffRepos.assertEquals("hints", hint, builder.toString());
    }

    void fails(String failedMsg) {
      try {
        tester.convertSqlToRel(factory, sql, decorrelate, trim);
        fail("Unexpected exception");
      } catch (AssertionError e) {
        assertThat(e.getMessage(), is(failedMsg));
      }
    }

    void warns(String expectWarning) {
      MockAppender appender = new MockAppender();
      MockLogger logger = new MockLogger();
      logger.addAppender(appender);
      try {
        tester.convertSqlToRel(factory, sql, decorrelate, trim);
      } finally {
        logger.removeAppender(appender);
      }
      appender.loggingEvents.add(expectWarning); // TODO: remove
      assertThat(expectWarning, is(in(appender.loggingEvents)));
    }

    SqlNode parseQuery() throws Exception {
      return tester.parseQuery(factory, sql);
    }

    RelNode toRel() {
      return tester.convertSqlToRel(factory, sql, decorrelate, trim).rel;
    }

    /** A shuttle to collect all the hints within the relational expression into a collection. */
    private static class HintCollector extends RelShuttleImpl {
      private final List<String> hintsCollect;

      HintCollector(List<String> hintsCollect) {
        this.hintsCollect = hintsCollect;
      }

      @Override public RelNode visit(TableScan scan) {
        if (scan.getHints().size() > 0) {
          this.hintsCollect.add("TableScan:" + scan.getHints());
        }
        return super.visit(scan);
      }

      @Override public RelNode visit(LogicalJoin join) {
        if (join.getHints().size() > 0) {
          this.hintsCollect.add("LogicalJoin:" + join.getHints());
        }
        return super.visit(join);
      }

      @Override public RelNode visit(LogicalProject project) {
        if (project.getHints().size() > 0) {
          this.hintsCollect.add("Project:" + project.getHints());
        }
        return super.visit(project);
      }

      @Override public RelNode visit(LogicalAggregate aggregate) {
        if (aggregate.getHints().size() > 0) {
          this.hintsCollect.add("Aggregate:" + aggregate.getHints());
        }
        return super.visit(aggregate);
      }

      @Override public RelNode visit(LogicalCorrelate correlate) {
        if (correlate.getHints().size() > 0) {
          this.hintsCollect.add("Correlate:" + correlate.getHints());
        }
        return super.visit(correlate);
      }

      @Override public RelNode visit(LogicalFilter filter) {
        if (filter.getHints().size() > 0) {
          this.hintsCollect.add("Filter:" + filter.getHints());
        }
        return super.visit(filter);
      }

      @Override public RelNode visit(LogicalUnion union) {
        if (union.getHints().size() > 0) {
          this.hintsCollect.add("Union:" + union.getHints());
        }
        return super.visit(union);
      }

      @Override public RelNode visit(LogicalIntersect intersect) {
        if (intersect.getHints().size() > 0) {
          this.hintsCollect.add("Intersect:" + intersect.getHints());
        }
        return super.visit(intersect);
      }

      @Override public RelNode visit(LogicalMinus minus) {
        if (minus.getHints().size() > 0) {
          this.hintsCollect.add("Minus:" + minus.getHints());
        }
        return super.visit(minus);
      }

      @Override public RelNode visit(LogicalSort sort) {
        if (sort.getHints().size() > 0) {
          this.hintsCollect.add("Sort:" + sort.getHints());
        }
        return super.visit(sort);
      }

      @Override public RelNode visit(LogicalValues values) {
        if (values.getHints().size() > 0) {
          this.hintsCollect.add("Values:" + values.getHints());
        }
        return super.visit(values);
      }

      @Override public RelNode visit(RelNode other) {
        if (other instanceof Window) {
          Window window = (Window) other;
          if (window.getHints().size() > 0) {
            this.hintsCollect.add("Window:" + window.getHints());
          }
        } else if (other instanceof Snapshot) {
          Snapshot snapshot = (Snapshot) other;
          if (snapshot.getHints().size() > 0) {
            this.hintsCollect.add("Snapshot:" + snapshot.getHints());
          }
        }
        return super.visit(other);
      }
    }
  }

  /** Mock appender to collect the logging events. */
  private static class MockAppender {
    final List<String> loggingEvents = new ArrayList<>();

    void append(String event) {
      loggingEvents.add(event);
    }
  }

  /** An utterly useless Logger; a placeholder so that the test compiles and
   * trivially succeeds. */
  private static class MockLogger {
    void addAppender(MockAppender appender) {
    }

    void removeAppender(MockAppender appender) {
    }
  }

  /** Define some tool members and methods for hints test. */
  private static class HintTools {
    //~ Static fields/initializers ---------------------------------------------

    static final String HINT = "properties(k1='v1', k2='v2'), index(ename), no_hash_join";

    static final RelHint PROPS_HINT = RelHint.builder("PROPERTIES")
        .hintOption("K1", "v1")
        .hintOption("K2", "v2")
        .build();

    static final RelHint IDX_HINT = RelHint.builder("INDEX")
        .hintOption("ENAME")
        .build();

    static final RelHint JOIN_HINT = RelHint.builder("NO_HASH_JOIN").build();

    static final HintStrategyTable HINT_STRATEGY_TABLE = createHintStrategies();

    //~ Methods ----------------------------------------------------------------

    /**
     * Creates mock hint strategies.
     *
     * @return HintStrategyTable instance
     */
    private static HintStrategyTable createHintStrategies() {
      return createHintStrategies(HintStrategyTable.builder());
    }

    /**
     * Creates mock hint strategies with given builder.
     *
     * @return HintStrategyTable instance
     */
    static HintStrategyTable createHintStrategies(HintStrategyTable.Builder builder) {
      return builder
        .hintStrategy("no_hash_join", HintPredicates.JOIN)
        .hintStrategy("time_zone", HintPredicates.SET_VAR)
        .hintStrategy("REPARTITION", HintPredicates.SET_VAR)
        .hintStrategy("index", HintPredicates.TABLE_SCAN)
        .hintStrategy("properties", HintPredicates.TABLE_SCAN)
        .hintStrategy(
            "resource", HintPredicates.or(
            HintPredicates.PROJECT, HintPredicates.AGGREGATE,
                HintPredicates.CALC, HintPredicates.VALUES, HintPredicates.FILTER))
        .hintStrategy("AGG_STRATEGY",
            HintStrategy.builder(HintPredicates.AGGREGATE)
                .optionChecker(
                    (hint, errorHandler) -> errorHandler.check(
                    hint.listOptions.size() == 1
                        && (hint.listOptions.get(0).equalsIgnoreCase("ONE_PHASE")
                        || hint.listOptions.get(0).equalsIgnoreCase("TWO_PHASE")),
                    "Hint {} only allows single option, "
                        + "allowed options: [ONE_PHASE, TWO_PHASE]",
                    hint.hintName)).build())
        .hintStrategy("use_hash_join",
          HintPredicates.or(
              HintPredicates.and(HintPredicates.CORRELATE, temporalJoinWithFixedTableName()),
              HintPredicates.and(HintPredicates.JOIN, joinWithFixedTableName())))
        .hintStrategy("breakable", HintPredicates.SETOP)
        .hintStrategy("async_merge", HintPredicates.SORT)
        .hintStrategy("mini_batch",
                HintPredicates.and(HintPredicates.WINDOW, HintPredicates.PROJECT))
        .hintStrategy("fast_snapshot", HintPredicates.SNAPSHOT)
        .hintStrategy("use_merge_join",
            HintStrategy.builder(
                HintPredicates.and(HintPredicates.JOIN, joinWithFixedTableName()))
                .excludedRules(EnumerableRules.ENUMERABLE_JOIN_RULE).build())
        .build();
    }

    /** Returns a {@link HintPredicate} for temporal join with specified table references. */
    private static HintPredicate temporalJoinWithFixedTableName() {
      return (hint, rel) -> {
        if (!(rel instanceof LogicalCorrelate)) {
          return false;
        }
        LogicalCorrelate correlate = (LogicalCorrelate) rel;
        Predicate<RelNode> isScan = r -> r instanceof TableScan;
        if (!(isScan.test(correlate.getLeft()))) {
          return false;
        }
        RelNode rightInput = correlate.getRight();
        Predicate<RelNode> isSnapshotOnScan = r -> r instanceof Snapshot
            && isScan.test(((Snapshot) r).getInput());
        RelNode rightScan;
        if (isSnapshotOnScan.test(rightInput)) {
          rightScan = ((Snapshot) rightInput).getInput();
        } else if (rightInput instanceof Filter
            && isSnapshotOnScan.test(((Filter) rightInput).getInput())) {
          rightScan = ((Snapshot) ((Filter) rightInput).getInput()).getInput();
        } else {
          // right child of correlate must be a snapshot on table scan directly or a Filter which
          // input is snapshot on table scan
          return false;
        }
        final List<String> tableNames = hint.listOptions;
        final List<String> inputTables = Stream.of(correlate.getLeft(), rightScan)
            .map(scan -> Util.last(scan.getTable().getQualifiedName()))
            .collect(Collectors.toList());
        return equalsStringList(inputTables, tableNames);
      };
    }

    /** Returns a {@link HintPredicate} for join with specified table references. */
    private static HintPredicate joinWithFixedTableName() {
      return (hint, rel) -> {
        if (!(rel instanceof LogicalJoin)) {
          return false;
        }
        LogicalJoin join = (LogicalJoin) rel;
        final List<String> tableNames = hint.listOptions;
        final List<String> inputTables = join.getInputs().stream()
            .filter(input -> input instanceof TableScan)
            .map(scan -> Util.last(scan.getTable().getQualifiedName()))
            .collect(Collectors.toList());
        return equalsStringList(tableNames, inputTables);
      };
    }

    /** Format the query with hint {@link #HINT}. */
    static String withHint(String sql) {
      return String.format(Locale.ROOT, sql, HINT);
    }
  }
}


text:
Copyright (c) 2012 Roland Yonaba

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--]]

-- Requiring depandancies
local Vec = require 'vector'
local Player = require 'player'
local Integrator = require 'integrator'
local Ui = require 'ui'

-- Initializing some vars
local F_damping, F_Left, F_Right, F_Up, F_gravity
local int_Functions = {}
local players
local showCommands
local ground_level
local fps, step_fps, limit_fps, max_fps, low_fps, step_dt, frame_time
local real_curve, real_curve_area, real_peak, real_range
local N_players = 0
local chart_ox, chart_oy = 260, 310

-- Command keys
local KEY_DEC_FPS = 'f'
local KEY_INC_FPS = 'g'
local KEY_JUMP = ' '
local KEY_QUIT = 'escape'
local KEY_MOVE_LEFT = 'left'
local KEY_MOVE_RIGHT = 'right'
local KEY_HIDE_INFO = 'tab'

-- Counts all available integrators and their names
-- We'll spawn one agent per integrator
for k,v in pairs(Integrator) do
  -- Counts available integrators
  N_players  = N_players + 1

  -- Keep track of some metrics
  int_Functions[N_players] = {
    name = k , func = v,
    acc = 0, vel = 0 ,
    jump_peak = 0, jump_range = 0, accuracy = 0,
    show = true}
end

-- Some hidden buttons to hide/unhide some agents and their stats
for i = 1, N_players do
  local button = Ui.addButton(350, 30 + 15 * i, 20, 10 )
  button:setCallback(function()
    int_Functions[i].show = not int_Functions[i].show
  end)
end

-- Some colors
local WHITE = {255, 255, 255, 255}
local BROWN = {150, 050, 000, 155}
local CBLUE  = {000, 200, 255, 255}
local GREY   = {100, 100, 155, 255}
local color_chart = {
  {255, 255, 255, 255},
  {000, 255, 255, 255},
  {255, 000, 000, 255},
  {000, 255, 000, 255},
  {000, 000, 255, 255},
  {255, 255, 000, 255},
}

-- Sets the cap-value for framerate
local function setFps(capped_fps)
    step_dt = 1/capped_fps
    frame_time = love.timer.getMicroTime()
end

-- Clamps a value between min/max bounds
local clamp = function (v, min, max)
  return v < min and min or (v > max and max or v)
end

-- Find the nearest multiple of m near n
local nearestMultiple = function (n, m)
  return n + (m - n % m)
end

-- Draws the chart legend
local draw_legend = function(agents)
  local x = 350

  -- Headers
  love.graphics.printf('Accel',x+80,15,60,'right')
  love.graphics.printf('Vel',x+140,15,60,'right')
  love.graphics.printf('Jmp height',x+200,15,60,'right')
  love.graphics.printf('Jmp range',x+260,15,60,'right')
  love.graphics.printf('Accur',x+320,15,60,'right')

  -- Real curve legend
  love.graphics.setColor(CBLUE)
  love.graphics.rectangle('fill',x, 30, 20, 10)
  love.graphics.print('Real',x+40,30)
  love.graphics.printf(('%.1f'):format(int_Functions[1].acc),x+80,30,60,'right')
  love.graphics.printf(('%.1f'):format(int_Functions[1].vel),x+140,30,60,'right')
  love.graphics.printf(('%.1f'):format(real_peak),x+200,30,60,'right')
  love.graphics.printf(('%.1f'):format(real_range),x+260,30,60,'right')
  love.graphics.printf('---',x+320,30,60,'right')

  -- Integrators, names and accuracies
  for i = 1, #int_Functions do
    if int_Functions[i].show then
      love.graphics.setColor(agents[i].color)
      love.graphics.rectangle('fill',x, 30 + 15 * i, 20, 10)
      love.graphics.print(('%s'):format(int_Functions[i].name),x+40,30 + 15 * i)
      love.graphics.printf(('%.1f'):format(int_Functions[i].acc),x+80,30 + 15 * i,60,'right')
      love.graphics.printf(('%.1f'):format(int_Functions[i].vel),x+140,30 + 15 * i,60,'right')
      love.graphics.printf(('%.1f'):format(int_Functions[i].jump_peak),x+200,30 + 15 * i,60,'right')
      love.graphics.printf(('%.1f'):format(int_Functions[i].jump_range),x+260,30 + 15 * i,60,'right')
      love.graphics.printf(('%.1f%%'):format(int_Functions[i].accuracy),x+320,30 + 15 * i,60,'right')
    else
      love.graphics.setColor(GREY)
      love.graphics.rectangle('fill',x, 30 + 15 * i, 20, 10)
    end
  end
end

-- Draws chart
local draw_chart = function(ox, oy, lenx, leny)
  lenx = lenx or 250
  leny = leny or 150
  love.graphics.setColor(WHITE)
  love.graphics.line(ox, oy, ox, oy-leny)
  love.graphics.line(ox, oy, ox + lenx, oy)
  love.graphics.line(ox - lenx, oy, ox, oy)
end

-- Real integration
local acos = math.acos
local cos, sin, tan = math.cos, math.sin, math.tan
local ceil, min = math.ceil, math.min
local real_integration = function(a, v, ox, oy)
  local curve = {ox, oy} -- Curve
  local t = 0  -- time counter
  local dt = 1/30  -- fixed timestep

  local v0 = v:mag()  -- initial speed
  local a0 = a:mag() -- initial speed
  local theta = acos(v.x / v0) -- jump angle
  local cost = cos(theta)
  local tant = tan(theta)
  local sint = sin(theta)

  local d = 2 * v0 * sint / a0 -- jump duration
  local samps = ceil(d/dt) -- number of timesteps to reach the jump duration

  -- Calculates the curve
  for i = 1,samps do
    t = t + dt
    local x = v0 * cost * t
    local tj = x/(v0 * cost)
    local y = 0.5 * a0 * tj * tj - (x * tant)
    local crossAxis = y > 0
    curve[#curve+1] = x + ox
    curve[#curve+1] = min(y,0) + oy
    if crossAxis then break end -- exit condition, when we cross the horizontal axis
  end

  return curve
end

-- Real curve plot
function plotCurve(c, ox, oy, color)
  -- Make sure we have enough vertices
  if #c > 2 then
    love.graphics.setLineWidth(2)
    love.graphics.setColor(color)
    love.graphics.line(c)
  end
end

-- Evaluates shadowed area, peak and range from a given jump curve
local max = math.max
local tArea = function(b1, b2, h) return (b1 + b2) * (h / 2) end
local evalStats = function(oy, curve)
  local area = 0
  local peak = 0
  local range = 0
  local nPoints = (#curve / 2)
  local i = 0
  for step = 1, nPoints-1 do
    i = i + 2
    local b1 = (oy - curve[i])
    local b2 = (oy - curve[i+2])
    local h = (curve[i+1] - curve[i-1])
    peak = max(peak, max(b1, b2))
    range = range + h
    area = area + tArea(b1, b2, h)
  end
  return area, peak, range
end

-- Sets the display font size
love.graphics.setFont(love.graphics.newFont(10))

function love.load()

  -- Window size (800x600 by default)
  W_W = love.graphics.getWidth()
  W_H = love.graphics.getHeight()
  ground_level = W_H - 20 -- Ground level

  -- Inits some agents
  players = {}
  for i = 1, N_players do
    players[i] = Player()
    players[i].height = players[i].height + 25 - (i-1) * 10
    players[i].pos:set(40,ground_level - players[i].height)
    players[i].color = color_chart[i]
    -- Attach an unique integrator to each agent
    players[i].integrate = int_Functions[i].func
  end

  -- Forces
  F_gravity = Vec(0,300) -- Acceleration, doesn't takes into account the mass
  F_Left = Vec(-100,0) -- Impulse/frame for left move
  F_Right = Vec(100,0) -- Impulse/frame for right move
  F_Up = Vec(0,-300) -- Acts on an agent velocity for the current frame, for jump
  F_damping = 0.9 -- damping factor (varies between 0 and 1)

  -- Real curve & stats
  real_curve = {}
  real_peak = 0
  real_range = 0

  -- Display command keys control
  showCommands = true

  -- FPS control settings
  -- User can set the cap-value beetween 300 and 3.
  low_fps = 3   -- The lowest value
  limit_fps = 300 -- The highest value
  step_fps = 5  -- Step_value
  max_fps = 30 -- Tracks the current cap value
  setFps(max_fps)  -- Starts at the lowest fps-value
end

function love.update(dt)
  -- Step dt
  frame_time = frame_time + step_dt
  fps = love.timer.getFPS()

  -- Let's make sure we're not updating with any dt higher than step_dt
  dt = min(dt, step_dt)

  -- Left move
  if love.keyboard.isDown(KEY_MOVE_LEFT) then
    for i = 1,N_players do
      -- To move agents, give them a constant impulse each frame
      -- as long as the input key is held down
      if players[i]:isOnGround(ground_level) then
        players[i]:addForce(F_Left)
      end
    end
  end

  -- Right move
  if love.keyboard.isDown(KEY_MOVE_RIGHT) then
    for i = 1,N_players do
      -- To move agents, give them a constant impulse each frame
      -- as long as the input key is held down
      if players[i]:isOnGround(ground_level) then
        players[i]:addForce(F_Right)
      end
    end
  end

  -- Jump
  if love.keyboard.isDown(KEY_JUMP) then
    for i = 1,N_players do
     if players[i]:isOnGround(ground_level) and not players[i].hasJumped then
        -- For jump, we act upon the velocity vector
        -- Only for the actual frame
        players[i]:addVel(F_Up)
        players[i].hasJumped = true

        -- Starts recording parabola for curve plotting
        players[i].trace = true
        players[i].jump_curve = {}
        players[i].jump_curve[1] = players[i].pos.x
        players[i].jump_curve[2] = players[i].pos.y

        -- Evaluates the real jump curve & stats
        if i==1 then
          real_curve = real_integration(players[i].acc, players[i].vel:clamp(players[i].vMax), chart_ox, chart_oy)
          real_curve_area, real_peak, real_range = evalStats(chart_oy, real_curve)
        end
      end
    end
  end

  -- Update agents, wraps them into the window bounds
  for i = 1,N_players do
    players[i]:update(dt, F_gravity, F_damping, ground_level)
    players[i]:wrap(0,W_W,0,ground_level)
    players[i]:recordCurve(ground_level) -- keep tracing the jump curve

    -- Evaluates stats from all integrators jump curve
    int_Functions[i].acc = players[i].acc:mag()
    int_Functions[i].vel = players[i].vel:mag()
    if not players[i].trace and #players[i].jump_curve > 0 then
      if real_curve_area > 0 then
        local area, peak, range = evalStats(players[i].jump_curve[2], players[i].jump_curve)
        int_Functions[i].accuracy = (area * 100) /real_curve_area
        int_Functions[i].jump_peak = peak
        int_Functions[i].jump_range = range
      end
    end
  end
end

function love.draw()

  -- Draws agents
  love.graphics.setLineWidth(1)
  for i = 1,N_players do
    if int_Functions[i].show then
      players[i]:draw(int_Functions[i].name)
      players[i]:plotCurve(chart_ox, chart_oy)
    end
  end

  -- Draws ground
  love.graphics.setColor(WHITE)
  love.graphics.line(0, ground_level, W_W, ground_level)

  -- Draws chart
  draw_chart(chart_ox, chart_oy)

  -- Plot Real curve
  plotCurve(real_curve, chart_ox, chart_ox, CBLUE)

  -- Draws info
  love.graphics.setColor(WHITE)
  love.graphics.print(('Current : %d FPS'):format(fps),10,10)
  love.graphics.print(('Current limit: %d FPS'):format(max_fps),10,25)
  love.graphics.print(('FPS Cap varies between [%d] and [%d] fps by steps of [%d] fps')
    :format(low_fps, limit_fps, step_fps),10,40)

  -- Draws legend
  draw_legend(players)

  -- Draws Ui
  Ui.draw()

  -- Prints command keys
  if showCommands then
    love.graphics.setColor(BROWN)
    love.graphics.rectangle('fill',500,400,250,130)
    love.graphics.setColor(WHITE)
    love.graphics.print([[Command keys:

    [F]: Cap down framerate
    [G]: Cap up framerate
    [Left/Right Arrows]: Move agents
    [Space]: Jump
    [Tab]: Hide/Show command keys
    [LMB] (On Chart): Show/Hide an agent
    [Esc]: Quit
    ]],510,410)

  end

  -- Fps capping
  local this_time = love.timer.getMicroTime()
  if frame_time <= this_time then
    frame_time = this_time
    return
  end
  love.timer.sleep(frame_time - this_time)

end

function love.keyreleased(k, u)
  -- Authorizes a new jump,
  -- so that agent can't jump again being in the "air".
  if k == ' ' then
    for i = 1,N_players do
      players[i].hasJumped = false
    end
  end
end

function love.keypressed(k, u)
  -- Command keys
  if k == KEY_DEC_FPS then
    max_fps = clamp(nearestMultiple(max_fps - step_fps-1,step_fps), low_fps, limit_fps)
    setFps(max_fps)
  elseif k == KEY_INC_FPS then
    max_fps = clamp(nearestMultiple(max_fps + 1,step_fps), low_fps, limit_fps)
    setFps(max_fps)
  elseif k == KEY_HIDE_INFO then
    showCommands = not showCommands
  elseif k == KEY_QUIT then
    love.event.push('quit')
  end
end


text:
<?php

$content_tpl->set_block("F_CONTENT", "B_WARNING_NO_ACCESS", "H_WARNING_NO_ACCESS");
$content_tpl->set_block("F_CONTENT", "B_WARNING", "H_WARNING");
$content_tpl->set_block("F_CONTENT", "B_EDIT_HEADADMIN_UNCHECKED", "H_EDIT_HEADADMIN_UNCHECKED");
$content_tpl->set_block("F_CONTENT", "B_EDIT_HEADADMIN_CHECKED", "H_EDIT_HEADADMIN_CHECKED");
$content_tpl->set_block("F_CONTENT", "B_EDIT_ADMIN", "H_EDIT_ADMIN");

// Access for headadmins only
if ($user['usertype_headadmin'])
{
  $id_user = intval($_REQUEST['opt']);
  $users_ref = dbQuery("SELECT * FROM `users` WHERE `id` = $id_user");
  $users_row = dbFetch($users_ref);
  $content_tpl->set_var("I_ID_USER", $id_user);
  $content_tpl->set_var("I_USERNAME", htmlspecialchars($users_row['username']));

  $season_users_ref = dbQuery("SELECT * FROM `season_users` " .
			       "WHERE `id_user` = $id_user AND `id_season` = {$season['id']}");
  $season_users_row = dbFetch($season_users_ref);
  if ($season_users_row['usertype_headadmin'])
  {
    $content_tpl->parse("H_EDIT_HEADADMIN_CHECKED", "B_EDIT_HEADADMIN_CHECKED");
  }
  else
  {
    $content_tpl->parse("H_EDIT_HEADADMIN_UNCHECKED", "B_EDIT_HEADADMIN_UNCHECKED");
  }
  $content_tpl->set_var("I_ID_SEASON", $season['id']);
  $content_tpl->parse("H_EDIT_ADMIN", "B_EDIT_ADMIN");
}
else
{
  $content_tpl->parse("H_WARNING_NO_ACCESS", "B_WARNING_NO_ACCESS");
  $content_tpl->parse("H_WARNING", "B_WARNING");
}

?>


text:
package com.intellij.openapi.application.ex;

public final class ProgressSlide {
  private final String myUrl;
  private final float myProgressRation;

  public ProgressSlide(String url, float progressRatio) {
    myUrl = url;
    myProgressRation = progressRatio;
  }

  public float getProgressRation() {
    return myProgressRation;
  }

  public String getUrl() {
    return myUrl;
  }
}


text:
using System.Windows.Automation;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Project;
using Microsoft.PythonTools.Project.Web;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;

namespace TestUtilities.UI.Python {
    class PythonProjectDebugProperties : AutomationWrapper {
        public PythonProjectDebugProperties(AutomationElement element)
            : base(element) {
        }

        public string LaunchMode {
            get {
                var launchMode = new ComboBox(FindByAutomationId("_launchModeCombo"));
                return launchMode.GetSelectedItemName();
            }
            set {
                var launchMode = new ComboBox(FindByAutomationId("_launchModeCombo"));
                launchMode.SelectItem(value);
            }
        }

        private string GetValue(string automationId) {
            var textBox = new TextBox(FindByAutomationId(automationId));
            return textBox.Value;
        }

        private void SetValue(string automationId, string value) {
            var textBox = new TextBox(FindByAutomationId(automationId));
            textBox.Value = value;
        }

        public string SearchPaths { get { return GetValue("_searchPaths"); } set { SetValue("_searchPaths", value); } }
        public string CommandLineArguments { get { return GetValue("_arguments"); } set { SetValue("_arguments", value); } }
        public string InterpreterArguments { get { return GetValue("_interpreterPath"); } set { SetValue("_interpreterPath", value); } }
        public string InterpreterPath { get { return GetValue("_interpArgs"); } set { SetValue("_interpArgs", value); } }
        public string WebBrowserUrl { get { return GetValue("_launchUrl"); } set { SetValue("_launchUrl", value); } }
        public string WebBrowserPort { get { return GetValue("_portNumber"); } set { SetValue("_portNumber", value); } }

        public string RunWebServerTarget { get { return GetValue("_runServerTarget"); } set { SetValue("_runServerTarget", value); } }
        public string RunWebServerArguments { get { return GetValue("_runServerArguments"); } set { SetValue("_runServerArguments", value); } }
        public string RunWebServerEnvironment { get { return GetValue("_runServerEnvironment"); } set { SetValue("_runServerEnvironment", value); } }
        public string DebugWebServerTarget { get { return GetValue("_debugServerTarget"); } set { SetValue("_debugServerTarget", value); } }
        public string DebugWebServerArguments { get { return GetValue("_debugServerArguments"); } set { SetValue("_debugServerArguments", value); } }
        public string DebugWebServerEnvironment { get { return GetValue("_debugServerEnvironment"); } set { SetValue("_debugServerEnvironment", value); } }

        public string RunWebServerTargetType {
            get {
                var comboBox = new ComboBox(FindByAutomationId("_runServerTargetType"));
                return comboBox.GetSelectedItemName();
            }
            set {
                var comboBox = new ComboBox(FindByAutomationId("_runServerTargetType"));
                comboBox.SelectItem(value);
            }
        }

        public string DebugWebServerTargetType {
            get {
                var comboBox = new ComboBox(FindByAutomationId("_debugServerTargetType"));
                return comboBox.GetSelectedItemName();
            }
            set {
                var comboBox = new ComboBox(FindByAutomationId("_debugServerTargetType"));
                comboBox.SelectItem(value);
            }
        }

        private static string PropertyValue(IPythonProject project, string property, string defaultValue = "") {
            return ((PythonProjectNode)project).Site.GetUIThread().Invoke(() => project.GetUnevaluatedProperty(property) ?? defaultValue);
        }

        public void AssertMatchesProject(IPythonProject project) {
            Assert.AreEqual(PropertyValue(project, PythonConstants.SearchPathSetting), SearchPaths, "SearchPaths does not match");
            Assert.AreEqual(PropertyValue(project, PythonConstants.CommandLineArgumentsSetting), CommandLineArguments, "CommandLineArguments does not match");
            Assert.AreEqual(PropertyValue(project, PythonConstants.InterpreterArgumentsSetting), InterpreterArguments, "InterpreterArguments does not match");
            Assert.AreEqual(PropertyValue(project, PythonConstants.InterpreterPathSetting), InterpreterPath, "InterpreterPath does not match");
            Assert.AreEqual(PropertyValue(project, PythonConstants.WebBrowserUrlSetting), WebBrowserUrl, "WebBrowserUrl does not match");
            Assert.AreEqual(PropertyValue(project, PythonConstants.WebBrowserPortSetting), WebBrowserPort, "WebBrowserPort does not match");
            Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerTargetProperty), RunWebServerTarget, "RunWebServerTarget does not match");
            Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerTargetTypeProperty, "script"), RunWebServerTargetType, "RunWebServerTargetType does not match");
            Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerArgumentsProperty), RunWebServerArguments, "RunWebServerArguments does not match");
            Assert.AreEqual(PropertyValue(project, PythonWebLauncher.RunWebServerEnvironmentProperty), RunWebServerEnvironment, "RunWebServerEnvironment does not match");
            Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerTargetProperty), DebugWebServerTarget, "DebugWebServerTarget does not match");
            Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerTargetTypeProperty, "script"), DebugWebServerTargetType, "DebugWebServerTargetType does not match");
            Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerArgumentsProperty), DebugWebServerArguments, "DebugWebServerArguments does not match");
            Assert.AreEqual(PropertyValue(project, PythonWebLauncher.DebugWebServerEnvironmentProperty), DebugWebServerEnvironment, "DebugWebServerEnvironment does not match");
        }
    }
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GalaSoft.MvvmLight.Platform.SL5")]
[assembly: AssemblyDescription("")]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("38191d74-57ae-4e46-85f7-c54059b9f197")]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Linq.Expressions;
using Elasticsearch.Net;
using Nest.Resolvers;

namespace Nest
{
	[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
	public class HistogramFacetDescriptor<T> : BaseFacetDescriptor<HistogramFacetDescriptor<T>, T> where T : class
	{
		[JsonProperty(PropertyName = "field")]
		internal PropertyPathMarker _Field { get; set; }

		[JsonProperty(PropertyName = "key_field")]
		internal PropertyPathMarker _KeyField { get; set; }

		[JsonProperty(PropertyName = "value_field")]
		internal PropertyPathMarker _ValueField { get; set; }

		[JsonProperty(PropertyName = "key_script")]
		internal string _KeyScript { get; set; }

		[JsonProperty(PropertyName = "value_script")]
		internal string _ValueScript { get; set; }

		[JsonProperty(PropertyName = "interval")]
		internal int? _Interval { get; set; }

		[JsonProperty(PropertyName = "time_interval")]
		internal string _TimeInterval { get; set; }

		[JsonProperty(PropertyName = "params")]
		[JsonConverter(typeof(DictionaryKeysAreNotPropertyNamesJsonConverter))]
		internal Dictionary<string, object> _Params { get; set; }

		public HistogramFacetDescriptor<T> OnField(string field)
		{
			field.ThrowIfNullOrEmpty("field");
			this._Field = field;
			return this;
		}
		public HistogramFacetDescriptor<T> OnField(Expression<Func<T, object>> objectPath)
		{
			objectPath.ThrowIfNull("objectPath");
			this._Field = objectPath;
			return this;
		}
		public HistogramFacetDescriptor<T> Interval(int interval)
		{
			this._Interval = interval;
			return this;
		}
		public HistogramFacetDescriptor<T> TimeInterval(string timeInterval)
		{
			timeInterval.ThrowIfNullOrEmpty("timeInterval");
			this._TimeInterval = timeInterval;
			return this;
		}
		public HistogramFacetDescriptor<T> TimeInterval(TimeSpan timespanInterval)
		{
			//now serializes TimeSpan.FromHours(1.5) to '01:30:00'
			//TODO check with integration test if this produces the correct result
			this._TimeInterval = timespanInterval.ToString();
			return this;
		}
		public HistogramFacetDescriptor<T> KeyField(Expression<Func<T, object>> objectPath)
		{
			objectPath.ThrowIfNull("objectPath");
			this._KeyField = objectPath;
			return this;
		}
		public HistogramFacetDescriptor<T> KeyField(string keyField)
		{
			keyField.ThrowIfNull("keyField");
			this._KeyField = keyField;
			return this;
		}
		public HistogramFacetDescriptor<T> KeyScript(string keyScript)
		{
			keyScript.ThrowIfNull("keyScript");
			this._KeyScript = keyScript;
			return this;
		}
		public HistogramFacetDescriptor<T> ValueField(Expression<Func<T, object>> objectPath)
		{
			objectPath.ThrowIfNull("objectPath");
			this._ValueField = objectPath;
			return this;
		}
		public HistogramFacetDescriptor<T> ValueField(string valueField)
		{
			valueField.ThrowIfNull("valueField");
			this._ValueField = valueField;
			return this;
		}
		public HistogramFacetDescriptor<T> ValueScript(string valueScript)
		{
			valueScript.ThrowIfNull("valueScript");
			this._ValueScript = valueScript;
			return this;
		}
		public HistogramFacetDescriptor<T> Params(Func<FluentDictionary<string, object>, FluentDictionary<string, object>> paramDictionary)
		{
			paramDictionary.ThrowIfNull("paramDictionary");
			this._Params = paramDictionary(new FluentDictionary<string, object>());
			return this;
		}
	}
}


text:
"use strict";

// https://github.com/rwaldron/exponentiation-operator

exports.experimental = true;

var build = require("../../helpers/build-binary-assignment-operator-transformer");
var t     = require("../../../types");

var MATH_POW = t.memberExpression(t.identifier("Math"), t.identifier("pow"));

build(exports, {
  operator: "**",

  build: function (left, right) {
    return t.callExpression(MATH_POW, [left, right]);
  }
});


text:
/*!
 * \file
 * \brief Class module::Encoder_BCH.
 */
#ifndef ENCODER_BCH_HPP_
#define ENCODER_BCH_HPP_

#include <vector>

#include "Tools/Code/BCH/BCH_polynomial_generator.hpp"
#include "Module/Encoder/Encoder.hpp"

namespace aff3ct
{
namespace module
{
template <typename B = int>
class Encoder_BCH : public Encoder<B>
{

protected:
	const int n_rdncy;       // number redundancy bits
	const std::vector<B> &g; // coefficients of the generator polynomial, g(x)
	std::vector<B> bb;       // coefficients of redundancy polynomial x^(length-k) i(x) modulo g(x)

public:
	Encoder_BCH(const int& K, const int& N, const tools::BCH_polynomial_generator<B>& GF);

	virtual ~Encoder_BCH() = default;

	virtual Encoder_BCH<B>* clone() const;

	bool is_codeword(const B *X_N);

protected:
	virtual void  _encode(const B *U_K, B *X_N, const size_t frame_id);
	virtual void __encode(const B *U_K, B *bb);
};
}
}

#endif // ENCODER_BCH_HPP_


text:
'''
Given a linked list, remove the nth node from the end of list and return its head.

For example,

   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.

'''

# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    # @param {ListNode} head
    # @param {integer} n
    # @return {ListNode}
    def removeNthFromEnd(self, head, n):
        p = head

        i = 0
        while i < n:
            p = p.next
            i += 1

        pre = head
        while p!= None and p.next != None:
            p = p.next
            pre = pre.next

        if p == None:
            head = head.next
        else:
            pre.next = pre.next.next

        return head

if __name__ == '__main__':
    so = Solution()

    n1 = ListNode(1)
    n2 = ListNode(2)